using CP.Cache.Redis; using CP.Cache.WebCache; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Reflection; using System.Web; namespace CP.Cache { public class WMCache { /// /// 本类实体 /// private static volatile WMCache instance = null; /// /// cache 接口 /// private static ICache mcs; /// /// redis接口 /// private static ICache rcs; /// /// 默认700分钟 /// public const int CacheTime = 700; /// /// 锁 /// private static object lockHelper = new object(); /// /// 初始化Cache /// private WMCache() { switch (CacheProvider) { case 0: mcs = new WebCacheManager(); //web memory cache break; case 1: rcs = new RedisManager(); //redis cache mcs = new WebCacheManager(); //web memory cache break; default: mcs = new WebCacheManager(); //web memory cache break; } } /// /// 获取缓存实例 /// /// public static WMCache GetCacheService() { if (instance == null) { lock (lockHelper) { if (instance == null) { instance = new WMCache(); } } } return instance; } /// /// 添加T到缓存 /// /// /// /// /// /// 是否使用redis public virtual void AddObject(string key, T o, int t = 60, bool IsRedis = false) { if (string.IsNullOrEmpty(key) || o == null) return; lock (lockHelper) { //HttpContext.Current.Response.Write("SetObject:" + key + "
"); if (IsRedis) { rcs.AddObject(key, o, t); } else { mcs.AddObject(key, o, t); } } } /// /// 根据Key获取key值 /// /// /// /// public virtual T GetObject(string key, bool IsRedis = false) { //StackTrace ss = new StackTrace(true); //MethodBase mb = ss.GetFrame(2).GetMethod(); //HttpContext.Current.Response.Write("名称空间:" + mb.DeclaringType.Namespace + ",类名:" + mb.DeclaringType.Name + ",方法名:" + mb.Name + "
"); //HttpContext.Current.Response.Write("Get:" + key + "

"); if (string.IsNullOrEmpty(key)) return default(T); lock (lockHelper) { if (IsRedis) { return rcs.GetObject(key); } else { return mcs.GetObject(key); } } } /// /// key是否存在... /// /// /// 是否使用redis /// public virtual bool IsExist(string key, bool IsRedis = false) { lock (lockHelper) { if (IsRedis) { return rcs.IsExist(key); } else { return mcs.IsExist(key); } } } public virtual List GetKeys(bool IsRedis = false) { lock (lockHelper) { if (IsRedis) { return rcs.GetKeys(); } else { return mcs.GetKeys(); } } } public virtual void RemoveObject(string key) { if (string.IsNullOrEmpty(key)) return; lock (lockHelper) { mcs.RemoveObject(key); rcs?.RemoveObject(key); } } /// /// 移出所有cache /// public virtual void RemoveAll() { lock (lockHelper) { mcs.RemoveAll(); rcs?.RemoveAll(); } } /// /// 批量移出cache /// /// public virtual void RemoveObjectByRegex(string key) { if (string.IsNullOrEmpty(key)) return; lock (lockHelper) { mcs.RemoveObjectByRegex(key); rcs?.RemoveObjectByRegex(key); } } /// /// 是否开启IsMemCached模型 /// 请查看web.config的参数配置 /// private static int CacheProvider { get { if (ConfigurationManager.AppSettings["CacheProvider"] != null) return Convert.ToInt32(ConfigurationManager.AppSettings["CacheProvider"]); return 0; } } } }