using Long.Core.Extensions;
using System.Runtime.Caching;
namespace Long.Utils.Cache
{
///
/// 缓存类
///
public class ObjectCaching
{
///
/// 添加缓存
///
/// 键
/// 值
/// 过期时间(秒)
public static void Add(string key, object value, long timeout = 60)
{
Add(key, value, timeout, null);
}
///
/// 添加缓存
///
/// 键
/// 值
/// 过期时间(秒)
/// 区域名称
///
public static void Add(string key, object value, long timeout, string regionName)
{
ObjectCache cache = MemoryCache.Default;
key.AssertNullOrWhiteSpace("缓存键名不能未空。");
if (timeout <= 0)
{
throw new ApplicationException("参数 timeout 的值不能小于1。");
}
var policy = new CacheItemPolicy()
{
SlidingExpiration = new TimeSpan(timeout * TimeSpan.TicksPerSecond),
};
cache.Add(key, value, policy, regionName);
}
///
/// 判断缓存内容是否存在
///
/// 键
///
public static bool Contains(string key)
{
return Contains(key, null);
}
///
/// 判断缓存内容是否存在
///
/// 键
/// 区域名
///
public static bool Contains(string key, string regionName)
{
ObjectCache cache = MemoryCache.Default;
key.AssertNullOrWhiteSpace("缓存键名不能未空。");
return cache.Contains(key, regionName);
}
///
/// 获取缓存内容
///
/// 泛型对象
/// 键
///
public static T Get(string key)
{
ObjectCache cache = MemoryCache.Default;
key.AssertNullOrWhiteSpace("缓存键名不能未空。");
return (T)cache.Get(key, null);
}
///
/// 获取缓存内容
///
/// 键
/// 区域名
///
public static T Get(string key, string regionName)
{
ObjectCache cache = MemoryCache.Default;
key.AssertNullOrWhiteSpace("缓存键名不能未空。");
return (T)cache.Get(key, regionName);
}
///
/// 删除缓存
///
///
public static void Remove(string key)
{
Remove(key, null);
}
///
/// 删除缓存
///
/// 键
/// 区域名
public static void Remove(string key, string regionName)
{
ObjectCache cache = MemoryCache.Default;
key.AssertNullOrWhiteSpace("缓存键名不能未空。");
cache.Remove(key, regionName);
}
}
}