Cache Helper类
using System; using System.Collections.Generic; using System.Web; using System.Collections; using System.Web.Caching; namespace DMSite.Common { /// <summary> /// 服务器缓存帮助类 /// </summary> public class CacheHelper { /// <summary> /// 创建缓存项的文件依赖 /// </summary> /// <param name="key">缓存Key</param> /// <param name="obj">object对象</param> /// <param name="fileName">文件绝对路径</param> public static void InsertFile(string key, object obj, string fileName) { //创建缓存依赖项 CacheDependency dep = new CacheDependency(fileName); //创建缓存 HttpRuntime.Cache.Insert(key, obj, dep); } /// <summary> /// 创建缓存项过期 /// </summary> /// <param name="key">缓存Key</param> /// <param name="obj">object对象</param> public static void Insert(string key, object obj) { if (obj != null) { if (IsExist(key)) { HttpRuntime.Cache[key] = obj; } else { int expires = ConvertHelper.ToInt(ConfigHelper.GetAppSettings("TimeCache")); HttpRuntime.Cache.Insert(key, obj, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, expires, 0)); } } } /// <summary> /// 判断缓存对象是否存在 /// </summary> /// <param name="strKey">缓存键值名称</param> /// <returns>是否存在true 、false</returns> public static bool IsExist(string strKey) { return HttpRuntime.Cache[strKey] != null; } /// <summary> /// 获取缓存对象 /// </summary> /// <param name="key">缓存Key</param> /// <returns>object对象</returns> public static object GetCache(string key) { if (string.IsNullOrEmpty(key)) return null; if (ConfigHelper.GetAppSettings("IsCache") == "false") { return null; } return HttpRuntime.Cache.Get(key); } /// <summary> /// 获取缓存对象 /// </summary> /// <typeparam name="T">T对象</typeparam> /// <param name="key">缓存Key</param> /// <returns></returns> public static T Get<T>(string key) { object obj = GetCache(key); return obj == null ? default(T) : (T)obj; } /// <summary> /// 移除指定数据缓存 /// </summary> public static void RemoveCache(string CacheKey) { System.Web.Caching.Cache _cache = HttpRuntime.Cache; _cache.Remove(CacheKey); } /// <summary> /// 移除全部缓存 /// </summary> public static void RemoveAllCache() { System.Web.Caching.Cache _cache = HttpRuntime.Cache; IDictionaryEnumerator CacheEnum = _cache.GetEnumerator(); while (CacheEnum.MoveNext()) { _cache.Remove(CacheEnum.Key.ToString()); } } } }