xinjiang/SGGL/BLL/Common/CacheHelper.cs

103 lines
2.7 KiB
C#

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