using System;
using System.Runtime.Caching;
namespace BLL
{
public class CacheHelper
{
private static readonly ObjectCache Cache = MemoryCache.Default;
///
/// 添加缓存项
///
/// 缓存键
/// 缓存值
/// 绝对过期时间
public static void Add(string key, object value, DateTimeOffset absoluteExpiration)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
Cache.Set(key, value, absoluteExpiration);
}
///
/// 获取缓存项(泛型)
///
/// 返回类型
/// 缓存键
/// 缓存值
public static T Get(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
object value = Cache[key];
if (value is T tValue)
{
return tValue;
}
return default(T);
}
///
/// 获取缓存项
///
/// 缓存键
/// 缓存值
public static object Get(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
return Cache[key];
}
///
/// 移除缓存项
///
/// 缓存键
public static void Remove(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
Cache.Remove(key);
}
///
/// 清空所有缓存
///
public static void Clear()
{
foreach (var item in Cache)
{
Cache.Remove(item.Key);
}
}
///
/// 检查缓存项是否存在
///
/// 缓存键
/// 是否存在
public static bool Exists(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException(nameof(key));
}
return Cache.Contains(key);
}
}
}