引入
using System.Web.Caching;
/*
Key//缓存名
Value//要缓存的对象
Dependencies//依赖项
AbsoluteExpiration//绝对过期时间
SlidingExpiration//相对过期时间
Priority//优先级
CacheItemRemovedCallback //缓存过期引发事件
*/
/// <summary>
/// 缓存
/// </summary>
/// <typeparam name="T"></typeparam>
public class CacheHelper<T>
{
/// <summary>
/// 获取缓存数据
/// </summary>
/// <param name="cachekey"></param>
/// <returns></returns>
public static T GetCache(string cachekey)
{
return (T)HttpRuntime.Cache[cachekey];
}
/// <summary>
/// 数据插入缓存(永不过期)
/// </summary>
/// <param name="cachekey"></param>
/// <param name="data"></param>
public static void SetCache(string cachekey, T data)
{
HttpRuntime.Cache.Insert(cachekey, data);
}
/// <summary>
/// 数据插入缓存(依赖)
/// </summary>
/// <param name="cachekey"></param>
/// <param name="data"></param>
/// <param name="dependencies">对文件或者目录的依赖</param>
public static void SetCache(string cachekey, T data, CacheDependency dependencies) //依赖
{
HttpRuntime.Cache.Insert(cachekey, data, dependencies);
}
/// <summary>
/// 数据插入缓存(绝对事件过期)
/// </summary>
/// <param name="cachekey"></param>
/// <param name="data"></param>
/// <param name="timeout"></param>
public static void SetCache(string cachekey, T data, TimeSpan timeout)
{
HttpRuntime.Cache.Insert(cachekey, data, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null);
}
/// <summary>
/// 设置缓存数据(绝对时间过期)
/// </summary>
/// <param name="cachekey"></param>
/// <param name="objObject"></param>
/// <param name="absoluteExpiration"></param>
/// <param name="slidingExpiration"></param>
public static void SetCache(string cachekey, T data, DateTime absoluteExpiration, TimeSpan slidingExpiration)
{
HttpRuntime.Cache.Insert(cachekey, data, null, absoluteExpiration, slidingExpiration);
}
/// <summary>
/// 移除指定缓存数据
/// </summary>
/// <param name="cachekey"></param>
public static void RemoveAllCache(string cachekey)
{
HttpRuntime.Cache.Remove(cachekey);
}
/// <summary>
/// 移除全部缓存
/// </summary>
public static void RemoveAllCache()
{
var cache = HttpRuntime.Cache;
var cacheEnum = cache.GetEnumerator();
while (cacheEnum.MoveNext())
{
cache.Remove(cacheEnum.Key.ToString());
}
}
}