using System; using System.Web; namespace WX.CRM.Common { public class CacheHelper { #region 判断Cache存在 /// /// 判断cahce是否存在 /// /// key /// public static bool Exists(string key) { bool result = false; if (HttpRuntime.Cache[key] != null) { result = true; } return result; } #endregion #region 获取Cache /// /// 获取缓存 /// /// 类型 /// Key /// public static T Get(string key) { try { T t = (T)HttpRuntime.Cache[key]; return t; } catch (Exception ex) { throw ex; } } /// /// 尝试获取某个缓存 /// /// /// /// /// public static bool TryGet(string key, ref T data) { try { data = (T)HttpRuntime.Cache[key]; return data != null; } catch (Exception ex) { throw ex; } } #endregion #region 设置Cache /// /// 设置缓存 /// /// 类型 /// key /// value public static void Set(string key, T t) { HttpRuntime.Cache.Insert(key, t); } /// /// 设置缓存 /// /// 类型 /// key /// value /// 过期时间 /// 是否为相对过期时间 public static void Set(string key, T t, DateTime expiresTime, bool isXD = true) { if (isXD) HttpRuntime.Cache.Insert(key, t, null, expiresTime, System.Web.Caching.Cache.NoSlidingExpiration); else HttpRuntime.Cache.Insert(key, t, null, expiresTime, TimeSpan.Zero); } /// /// 文件组依赖缓存 /// /// 类型 /// key /// value /// 过期时间 /// 文件组 public static void Set(string key, T t, DateTime expiresTime, string[] filePaths) { HttpRuntime.Cache.Insert(key, t, new System.Web.Caching.CacheDependency(filePaths), expiresTime, TimeSpan.Zero); } /// /// 文件依赖缓存 /// /// 类型 /// key /// value /// 过期时间 /// 文件 public static void Set(string key, T t, DateTime expiresTime, string filePath) { HttpRuntime.Cache.Insert(key, t, new System.Web.Caching.CacheDependency(filePath), expiresTime, TimeSpan.Zero); } #endregion #region 删除缓存 public static void Remove(string key) { if (Exists(key)) { HttpRuntime.Cache.Remove(key); } } #endregion #region 缓存处理 static CacheHelper lockobj = new CacheHelper(); /// /// 检查缓存是否存在 /// /// /// /// public static bool CheckTheCacheAndSava(string userName) { bool bExists = false; lock (lockobj) { bExists = HttpRuntime.Cache[userName] != null; if (!bExists) { HttpRuntime.Cache.Add(userName, "1", null, DateTime.Now.AddSeconds(120), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null); } } return bExists; } public static void RemoveRegCache(string userName) { CacheHelper.Remove(userName); } #endregion } }