using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Caching; namespace Cache.WebCache { /// /// 默认的.net WebCache接口实现 /// public class WebCache { protected static volatile System.Web.Caching.Cache webCache = HttpRuntime.Cache; /// /// 判断值是否存在.. /// /// /// public bool IsExist(string key) { if (string.IsNullOrEmpty(key)) return false; return webCache[key] != null; } /// /// 写入某个Cache /// /// 键 /// 对像 public void AddObject(string key, T o, int t = 0) { if (String.IsNullOrEmpty(key) || o == null) return; if (t == 0) t = int.Parse(ConfigurationManager.AppSettings["OutTime"]); CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(onRemove); webCache.Insert(key, o, null, System.DateTime.Now.AddMinutes(t), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, callBack); } /// /// 取某个key对应的object值 /// /// 键 /// public T GetObject(string key) { if (!String.IsNullOrEmpty(key)) return (T)webCache.Get(key); return default(T); } /// /// 移出某个Cache /// /// 键 public void RemoveObject(string key) { if (!String.IsNullOrEmpty(key)) webCache.Remove(key); } /// /// 批量移出类型key的对像 /// /// public void RemoveObjectByRegex(string pattern) { if (!string.IsNullOrEmpty(pattern)) { IDictionaryEnumerator enu = webCache.GetEnumerator(); while (enu.MoveNext()) { string key = enu.Key.ToString(); if (key.IndexOf(pattern, StringComparison.CurrentCultureIgnoreCase) != -1) { RemoveObject(key); } } } } /// /// 移出所有Cache /// public void RemoveAll() { IDictionaryEnumerator enu = webCache.GetEnumerator(); while (enu.MoveNext()) { RemoveObject(enu.Key.ToString()); } } public void onRemove(string key, object val, CacheItemRemovedReason reason) { switch (reason) { case CacheItemRemovedReason.DependencyChanged: //更新缓存映射表 break; case CacheItemRemovedReason.Expired: //更新缓存映射表 break; case CacheItemRemovedReason.Removed: break; case CacheItemRemovedReason.Underused: break; default: break; } } /// /// 返回所有键值 /// /// public List GetKeys() { List list = new List(); IDictionaryEnumerator enu = webCache.GetEnumerator(); while (enu.MoveNext()) { list.Add(enu.Key.ToString()); } return list; } } }