先建立一個CacheHelper.cs類,代碼以下:數據庫
- using System;
- using System.Web;
- using System.Collections;
- using System.Web.Caching;
-
- public class CacheHelper
- {
-
-
-
-
- public static object GetCache(string cacheKey)
- {
- var objCache = HttpRuntime.Cache.Get(cacheKey);
- return objCache;
- }
-
-
-
- public static void SetCache(string cacheKey, object objObject)
- {
- var objCache = HttpRuntime.Cache;
- objCache.Insert(cacheKey, objObject);
- }
-
-
-
- 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.Now.AddSeconds(timeout), TimeSpan.Zero, CacheItemPriority.High, null);
- }
- catch (Exception)
- {
-
- }
- }
-
-
-
- public static void RemoveAllCache(string cacheKey)
- {
- var cache = HttpRuntime.Cache;
- cache.Remove(cacheKey);
- }
-
-
-
- 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;
- }
測試結果也貼上來看看好了:spa

首次加載進來是爲null,而後讀取數據庫,添加進緩存,當前返回前臺的是從數據庫中取出的數據。.net

刷新頁面,發現緩存中已經有了讀出的30條數據,3d

而後接下來走,返回緩存中的數據:blog

大體這些了。ip
Endget