因為之前用的是Redis,准備用繼續Redis緩存某些小table的數據(主外鍵之類的),無奈不知道外網地址,問老大,曰:用Cache做吧。好吧......
網上找了一番,好多缺少引用的,添加了也沒好,弄了大概一個多小時,發現很無奈啊,突然想到以前的項目里面好像有用過吼~
簡直不要太容易啊~~~
下面步入正題了:
先創建一個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