因为之前用的是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();//从数据库取出
|
请发表评论