原文:https://www.cnblogs.com/xuhongfei/p/8951878.html
先创建一个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;
- }
测试结果也贴上来看看好了:
首次加载进来是为null,然后读取数据库,添加进缓存,当前返回前台的是从数据库中取出的数据。
刷新页面,发现缓存中已经有了读出的30条数据,
然后接下来走,返回缓存中的数据:
大致这些了。
End
C# Cache缓存读取设置
原文:https://www.cnblogs.com/zhang1f/p/11342765.html