#region Copyright (C) 2016 Kevin (OSS开源系列) 公众号:OSSCore
/***************************************************************************
* 文件功能描述:全局插件 - 缓存插件默认实现
*
* 创建人: Kevin
* 创建人Email:1985088337@qq.com
*
*
*****************************************************************************/
#endregion
using System;
using Microsoft.Extensions.Caching.Memory;
namespace OSS.Tools.Cache
{
///
///
///
public class DefaultToolCache : IToolCache
{
private static readonly MemoryCache _cache=new MemoryCache(new MemoryCacheOptions());
///
/// 添加缓存
/// 如果存在则更新
///
/// 添加缓存对象类型
/// 添加对象的key
/// 值
/// 相对过期的TimeSpan 如果使用固定时间 =TimeSpan.Zero
/// 绝对过期时间,不为空则按照绝对过期时间计算
/// 是否添加成功
[Obsolete]
public bool AddOrUpdate(string key, T obj, TimeSpan slidingExpiration, DateTime? absoluteExpiration = null)
{
return Add(key, obj, slidingExpiration, absoluteExpiration, true);
}
///
/// 添加时间段过期缓存
/// 如果存在则更新
///
/// 添加缓存对象类型
/// 添加对象的key
/// 值
/// 相对过期的TimeSpan
/// 是否添加成功
public bool Set(string key, T obj, TimeSpan slidingExpiration)
{
return Add(key, obj, slidingExpiration, null, true);
}
///
/// 添加固定过期时间缓存,如果存在则更新
///
/// 添加缓存对象类型
/// 添加对象的key
/// 值
/// 绝对过期时间,不为空则按照绝对过期时间计算
/// 是否添加成功
public bool Set(string key, T obj, DateTime absoluteExpiration)
{
return Add(key, obj, TimeSpan.Zero, absoluteExpiration, true);
}
///
///
///
///
///
///
///
///
///
///
private static bool Add(string key, T obj, TimeSpan slidingExpiration, DateTime? absoluteExpiration,
bool isUpdate)
{
if (slidingExpiration == TimeSpan.Zero && absoluteExpiration == null)
throw new ArgumentNullException("slidingExpiration", "缓存过期时间不正确,需要设置固定过期时间或者相对过期时间");
var opt = new MemoryCacheEntryOptions();
if (absoluteExpiration != null)
opt.AbsoluteExpiration = new DateTimeOffset(absoluteExpiration.Value);
else
opt.SlidingExpiration = slidingExpiration;
_cache.Set(key, obj, opt);
return true;
}
///
/// 获取缓存对象
///
/// 获取缓存对象类型
/// key
/// 获取指定key对应的值
public T Get(string key)
{
return _cache.Get(key);
}
///
/// 移除缓存对象
///
///
/// 是否成功
public bool Remove(string key)
{
_cache.Remove(key);
return true;
}
}
}