using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Caching; using System.Web.Hosting; namespace FangYar.Common { /// /// Caching 的摘要说明 /// public class CacheHelper { /// /// 获取当前应用程序指定CacheKey的Cache值 /// /// /// y public static object GetCache(string CacheKey) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; return objCache[CacheKey]; } /// /// 设置当前应用程序指定CacheKey的Cache值 /// /// /// public static void SetCache(string CacheKey, object objObject) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject); } /// /// 设置当前应用程序指定CacheKey的Cache值 /// /// /// public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration); } /// /// 设置数据缓存 /// public static void SetCache(string CacheKey, object objObject, int timeout = 7200) { try { if (objObject == null) return; var objCache = HttpRuntime.Cache; //相对过期 //objCache.Insert(cacheKey, objObject, null, DateTime.MaxValue, timeout, CacheItemPriority.NotRemovable, null); //绝对过期时间 objCache.Insert(CacheKey, objObject, null, DateTime.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null); } catch (Exception) { //throw; } } /// /// 清除单一键缓存 /// /// public static void RemoveKeyCache(string CacheKey) { try { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Remove(CacheKey); } catch { } } /// /// 清除所有缓存 /// public static void RemoveAllCache() { System.Web.Caching.Cache _cache = HttpRuntime.Cache; IDictionaryEnumerator CacheEnum = _cache.GetEnumerator(); if (_cache.Count > 0) { ArrayList al = new ArrayList(); while (CacheEnum.MoveNext()) { al.Add(CacheEnum.Key); } foreach (string key in al) { _cache.Remove(key); } } } /// /// 清除所有缓存 /// public static void RemoveAllCache2() { var cache = HttpRuntime.Cache; var cacheEnum = cache.GetEnumerator(); while (cacheEnum.MoveNext()) { cache.Remove(cacheEnum.Key.ToString()); } } /// /// 以列表形式返回已存在的所有缓存 /// /// public static ArrayList ShowAllCache() { ArrayList al = new ArrayList(); System.Web.Caching.Cache _cache = HttpRuntime.Cache; if (_cache.Count > 0) { IDictionaryEnumerator CacheEnum = _cache.GetEnumerator(); while (CacheEnum.MoveNext()) { al.Add(CacheEnum.Key); } } return al; } } }