先創建一個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,然後讀取數據庫,添加進緩存,當前返回前臺的是從數據庫中取出的數據。
刷新頁面,發現緩存中已經有了讀出的30條數據,
然後接下來走,返回緩存中的數據:
大致這些了。
End