using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Caching; namespace CallCenterApi.Common { public class CacheHelper { /// /// 创建缓存项的文件依赖 /// /// 缓存Key /// object对象 /// 文件绝对路径 public static void Insert(string key, object obj, string fileName) { //创建缓存依赖项 CacheDependency dep = new CacheDependency(fileName); //创建缓存 HttpContext.Current.Cache.Insert(key, obj, dep); } /// /// 创建缓存,无过期时间 /// /// /// public static void Insert(string key, object obj) { HttpContext.Current.Cache.Insert(key, obj); } /// /// 创建缓存项过期 /// /// 缓存Key /// object对象 /// 过期时间(分钟) public static void Insert(string key, object obj, int expires) { //最后一次访问开始计算 //HttpContext.Current.Cache.Insert(key, obj, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, expires, 0)); //从设置时开始计算 HttpContext.Current.Cache.Insert(key, obj, null, DateTime.UtcNow.AddMinutes(expires), Cache.NoSlidingExpiration); } /// /// 创建缓存项过期 /// /// 缓存Key /// object对象 /// 过期时间(分钟) /// 缓存清理优先级 public static void Insert(string key, object obj, int expires, CacheItemPriority priority) { //从设置时开始计算 HttpContext.Current.Cache.Insert(key, obj, null, DateTime.UtcNow.AddMinutes(expires), Cache.NoSlidingExpiration, priority, null); } /// /// 创建缓存项过期 /// /// 缓存Key /// object对象 /// 过期时间(分钟) /// 缓存清理优先级 public static void Insert(string key, object obj, int expires, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback) { //从设置时开始计算 HttpContext.Current.Cache.Insert(key, obj, null, DateTime.UtcNow.AddMinutes(expires), Cache.NoSlidingExpiration, priority, onRemoveCallback); } /// /// 获取缓存对象 /// /// 缓存Key /// object对象 public static object Get(string key) { if (string.IsNullOrEmpty(key)) { return null; } return HttpContext.Current.Cache.Get(key); } /// /// 获取缓存对象 /// /// T对象 /// 缓存Key /// public static T Get(string key) { object obj = Get(key); return obj == null ? default(T) : (T)obj; } /// /// 移出Cache对象 /// /// public static void Remove(string Key) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Remove(Key); } /// /// 移除所有Cache对象 /// public static void RemoveAll() { System.Web.Caching.Cache cache = HttpRuntime.Cache; IDictionaryEnumerator cacheEnum = cache.GetEnumerator(); ArrayList al = new ArrayList(); while (cacheEnum.MoveNext()) { al.Add(cacheEnum.Key); } foreach (string key in al) { cache.Remove(key); } } } }