先建立一個CacheHelper.cs類,代碼以下:數據庫
using System; using System.Web; using System.Collections; using System.Web.Caching; public class CacheHelper { /// <summary> /// 獲取數據緩存 /// </summary> /// <param name="cacheKey">鍵</param> public static object GetCache(string cacheKey) { var objCache = HttpRuntime.Cache.Get(cacheKey); return objCache; } /// <summary> /// 設置數據緩存 /// </summary> public static void SetCache(string cacheKey, object objObject) { var objCache = HttpRuntime.Cache; objCache.Insert(cacheKey, objObject); } /// <summary> /// 設置數據緩存 /// </summary> 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; } } /// <summary> /// 移除指定數據緩存 /// </summary> public static void RemoveAllCache(string cacheKey) { var cache = HttpRuntime.Cache; cache.Remove(cacheKey); } /// <summary> /// 移除所有緩存 /// </summary> public static void RemoveAllCache() { var cache = HttpRuntime.Cache; var cacheEnum = cache.GetEnumerator(); while (cacheEnum.MoveNext()) { cache.Remove(cacheEnum.Key.ToString()); } } }
而後是調用:緩存
public IEnumerable<CompanyModel> FindCompanys() { var cache = CacheHelper.GetCache("commonData_Company");//先讀取 if (cache == null)//若是沒有該緩存 { var queryCompany = _base.CompanyModel();//從數據庫取出 var enumerable = queryCompany.ToList(); CacheHelper.SetCache("commonData_Company", enumerable);//添加緩存 return enumerable; } var result = (List<CompanyModel>)cache;//有就直接返回該緩存 return result; }
測試結果:測試
首次加載進來是爲null,而後讀取數據庫,添加進緩存,當前返回前臺的是從數據庫中取出的數據。blog
刷新頁面,發現緩存中已經有了讀出的30條數據,string
而後接下來走,返回緩存中的數據:it