Asp.net通用的应用程序缓存方法
/********************************************************* * 创 建 人:事理 * 创建时间:2012-09-03 11:56 * 版权所有:Copyright © * 描 述:通用应用程序缓存辅助类 * *******************************************************/ using System; using System.Data; using System.Web; using System.Collections.Generic; public static class CacheHelper { public delegate T GetDataMethod<T>();//获取数据的方法 /// <summary> /// 通用应用程序缓存方法,缓存数据未指定时间 /// </summary> /// <typeparam name="T">缓存数据的类型,一般是集合,如IList<UsersData></typeparam> /// <param name="key">键</param> /// <param name="cacheTimeout">缓存时间,分钟单位</param> /// <param name="getDataMethod">获取数据的方法</param> /// <returns>数据列表</returns> public static T GetCache<T>(string key, DateTime cacheTimeout, GetDataMethod<T> getDataMethod) { //T dataList = getDataMethod(); //return dataList; if (HttpRuntime.Cache[key] == null) { T dataList = getDataMethod(); HttpRuntime.Cache.Add(key, dataList, null, cacheTimeout, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.High, null); return dataList; } return (T)HttpRuntime.Cache[key]; } /// <summary> /// 移除应用程序缓存 /// </summary> /// <param name="key">键</param> public static void RemoveCacheByKey(string key) { HttpRuntime.Cache.Remove(key); } /// <summary> /// 移除Key相似的缓存 /// </summary> /// <param name="similarKey">key相似的部分</param> public static void RemoveCacheBySimilarKey(string similarKey) { System.Collections.IDictionaryEnumerator cacheEnum = HttpRuntime.Cache.GetEnumerator(); List<string> keys = new List<string>(); while (cacheEnum.MoveNext()) { if (cacheEnum.Key.ToString().Contains(similarKey)) keys.Add(cacheEnum.Key.ToString()); } for (int i = 0; i < keys.Count; i++) { HttpRuntime.Cache.Remove(keys[i]); } } }
//使用示例 rptTop.DataSource = CacheHelper.GetCache("Menu", new CacheHelper.GetDataMethod<IList<PlateData>>(
delegate() { return PlateBll.GetAllByPlateType(new int[] { 1 }, 0, new int[] { 0, 1 }); }
));
rptTop.DataBind();