.NET MVC中缓存的使用
使用缓存可以提高网站性能,减轻对数据库的压力,提高用户访问网站的速度。在.NET MVC中,我们可以使用输出缓存和数据缓存达到储存常用且不易改变的数据。
输出缓存:
在Action前添加[OutputCache]标签:
[OutputCache(Duration = 600)] public ActionResult Content(string code, int ID) { // return View(); }
常用参数说明:
Duration:缓存时间,通常情况下是必须的,以秒为单位。
Location:页面缓存位置,默认为Any(缓存在浏览器、代理服务器端、Web服务器端),当被设置为None(不进行缓存)时,可不设置Duration。
VaryByParam:向Action传参时,根据哪些参数对输出进行缓存。
//只当传入的code不同时,会缓存不同的输出 [OutputCache(Duration = 600, VaryByParam = "code")] public ActionResult PositionTree(String code, int ID) //对所有传入参数进行不同的缓存 [OutputCache(Duration = 600, VaryByParam = "*")] //缓存与参数无关,此Action只缓存一份 [OutputCache(Duration = 600, VaryByParam = "none")]
CacheProfile:设置此Action关联的缓存设置名称,缓存设置写在Web.config中。
[OutputCache(CacheProfile = "ServerOnly")]
<caching> <outputCacheSettings> <outputCacheProfiles> <add name="ServerOnly" duration="60" location="Server" /> </outputCacheProfiles> </outputCacheSettings> </caching>
数据缓存:
使用HttpContext.Cache:
HttpContext.Cache["key"] = "value";
Cache和Application类似,为应用程序级(Session为用户会话级),采用键(string)值(Object)对存储数据。
如何添加Cache:
// 将指定项添加到 System.Web.Caching.Cache 对象,该对象具有依赖项、过期和优先级策略 // 以及一个委托(可用于在从 Cache 移除插入项时通知应用程序)。 HttpContext.Cache.Add(key, value,dependencies,absoluteExpiration,slidingExpiration,priority,onRemoveCallback); // 从 System.Web.Caching.Cache 对象检索指定项。 // key: 要检索的缓存项的标识符。 // 返回结果: 检索到的缓存项,未找到该键时为 null。 HttpContext.Cache.Insert(key,value); // 同Cache.Insert HttpContext.Cache[key] = value; //参数说明: //key:用于引用该对象的缓存键。 //value:要插入缓存中的对象。 //dependencies:该项的文件依赖项或缓存键依赖项。当任何依赖项更改时,该对象即无效, // 并从缓存中移除。如果没有依赖项,则此参数包含 null。 //absoluteExpiration:所插入对象将过期并被从缓存中移除的时间。 // 如果使用绝对过期,则 slidingExpiration 参数必须为Cache.NoSlidingExpiration。 //slidingExpiration:最后一次访问所插入对象时与该对象过期时之间的时间间隔。如果该值等效于 20 分钟, // 则对象在最后一次被访问 20 分钟之后将过期并被从缓存中移除。如果使用可调过期,则 // absoluteExpiration 参数必须为System.Web.Caching.Cache.NoAbsoluteExpiration。 //priority:该对象相对于缓存中存储的其他项的成本,由System.Web.Caching.CacheItemPriority 枚举表示。 // 该值由缓存在退出对象时使用;具有较低成本的对象在具有较高成本的对象之前被从缓存移除。 //onRemoveCallback:在从缓存中移除对象时将调用的委托(如果提供)。 // 当从缓存中删除应用程序的对象时,可使用它来通知应用程序。
Cache.Add与Cache.Insert的区别:
Cache.Add 需要完整的参数,且当Cache中存在插入的键时会出错。
Cache.Insert 最少需要key和value参数,当Cache存在插入的键时会覆盖掉原先的值。
移除Cache:
HttpContext.Cache.Remove(key);
Cache过期时间设置:
//设置绝对过期时间,slidingExpiration 参数必须为System.Web.Caching.Cache.NoSlidingExpiration HttpContext.Cache.Insert("key", "value", null, DateTime.Parse("2015-12-31 00:00:00"), Cache.NoSlidingExpiration); //设置最后一次访问缓存项与超期时间的间隔,absoluteExpiration 参数必须为System.Web.Caching.Cache.NoAbsoluteExpiration HttpContext.Cache.Insert("key", "value", null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(60));