一、概述
缓存是将信息(数据或页面)放在内存中以避免频繁的数据库存储或执行整个页面的生命周期,直到缓存的信息过期或依赖变更才再次从数据库中读取数据或重新执行页面的生命周期。在系统优化过程中,缓存是比较普遍的优化做法和见效比较快的做法。
MVC缓存本质上还是.NET的一套缓存体系,只不过该缓存体系应用在了MVC框架上。
缓存是一种以空间换时间的技术, 比如, CPU的二级缓存,Windows的文件缓存。减少服务器的负荷,默认存放在内存里面,不过是可以修改的。缓存存在失效的情况。Asp.net 缓存主要分为页面缓存,数据源缓存,数据缓存。
缓存代码的位置:
[1] 页面缓存: <%@OutPutCache Duration="15" VaryByParam="none" %>
[2] Contorller 缓存: [OutputCache(Duration = 10)]
[3] Action 缓存: [OutputCache(Duration = 10)]
缓存的常用场景:
数据被频繁的使用,并且很少发生变化或对即时性的要求不高。
二、Control 缓存
Control 缓存即是把缓存应用到整个Control 上,该Control 下的所有Action都会被缓存起来。Control 缓存的粒度比较粗,应用也比较少些。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcCache.Control.Controllers { [OutputCache(Duration = 10)] public class ControlController : Controller { // GET: /Home/ public ActionResult Index() { ViewBag.CurrentTime = System.DateTime.Now; return View(); } public ActionResult Index1() { ViewBag.CurrentTime = System.DateTime.Now; return View(); } } }
在名为Control的Control中加入了OutputCache,并设置持续时间为10秒(Duration=10),即每10秒后过期当再次触发时更新缓存。
三、Action 缓存
即把缓存用到Action上,Action缓存为比较常用的缓存方式,该方式粒度细一些。使用方法类似Control缓存。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcCache.Control.Controllers { //Control不加缓存 public class ActionController : Controller { //该Index的Action加缓存 [OutputCache(Duration = 10)] public ActionResult Index() { ViewBag.CurrentTime = System.DateTime.Now; return View(); } //该Action不加缓存 public ActionResult Index1() { ViewBag.CurrentTime = System.DateTime.Now; return View(); }
} }
四、使用配置文件
当我们需要将N个Control或Action加入缓存,并且缓存的参数是一致的情况下,我们可以把相关的设置放到Web.config中,并在程序中加入相应的配置。同时,在配置文件中配置缓存参数将更加灵活方便。
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <appSettings> <add key="webpages:Version" value="2.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="PreserveLoginUrl" value="true" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> </appSettings> <system.web> <!--配置缓存--> <caching> <outputCacheSettings> <outputCacheProfiles> <add name="TestConfigCache" duration="10"/> </outputCacheProfiles> </outputCacheSettings> </caching> <!--配置缓存--> <httpRuntime targetFramework="4.5" /> <compilation debug="true" targetFramework="4.5" /> <pages> <namespaces> <add namespace="System.Web.Helpers" /> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="System.Web.WebPages" /> </namespaces> </pages> </system.web> <system.webServer> <validation validateIntegratedModeConfiguration="false" /> <handlers> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer> </configuration>
配置缓存节只需要将其放在system.web节下即可,以下是使用的方法:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcCache.Control.Controllers { public class ConfigController : Controller { //TestConfigCache为在配置文件中配置的缓存节 [OutputCache(CacheProfile = "TestConfigCache")] public ActionResult Index() { ViewBag.CurrentTime = System.DateTime.Now; return View(); }
}
}
注:当Control与Action都应用了缓存时,以Action的缓存为主。
五、OutputCache 常用参数
下面代码为mvc4的OutputCache的定义,由于使用的是英文版本IDE和框架,因此注释全部为英文。后面的讲解主要讲解常用的属性,此处不包含对于缓存依赖的讲解使用方法。
各个属性的详细说明及使用请查阅MSDN,链接地址如下:https://msdn.microsoft.com/zh-cn/library/system.web.mvc.outputcacheattribute.aspx
using System; using System.Web.UI; namespace System.Web.Mvc { // Summary: // Represents an attribute that is used to mark an action method whose output // will be cached. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public class OutputCacheAttribute : ActionFilterAttribute, IExceptionFilter { // Summary: // Initializes a new instance of the System.Web.Mvc.OutputCacheAttribute class. public OutputCacheAttribute(); // Summary: // Gets or sets the cache profile name. // // Returns: // The cache profile name. public string CacheProfile { get; set; } // // Summary: // Gets or sets the child action cache. // // Returns: // The child action cache. public static System.Runtime.Caching.ObjectCache ChildActionCache { get; set; } // // Summary: // Gets or sets the cache duration, in seconds. // // Returns: // The cache duration. public int Duration { get; set; } // // Summary: // Gets or sets the location. // // Returns: // The location. public OutputCacheLocation Location { get; set; } // // Summary: // Gets or sets a value that indicates whether to store the cache. // // Returns: // true if the cache should be stored; otherwise, false. public bool NoStore { get; set; } // // Summary: // Gets or sets the SQL dependency. // // Returns: // The SQL dependency. public string SqlDependency { get; set; } // // Summary: // Gets or sets the vary-by-content encoding. // // Returns: // The vary-by-content encoding. public string VaryByContentEncoding { get; set; } // // Summary: // Gets or sets the vary-by-custom value. // // Returns: // The vary-by-custom value. public string VaryByCustom { get; set; } // // Summary: // Gets or sets the vary-by-header value. // // Returns: // The vary-by-header value. public string VaryByHeader { get; set; } // // Summary: // Gets or sets the vary-by-param value. // // Returns: // The vary-by-param value. public string VaryByParam { get; set; } // Summary: // Returns a value that indicates whether a child action cache is active. // // Parameters: // controllerContext: // The controller context. // // Returns: // true if the child action cache is active; otherwise, false. public static bool IsChildActionCacheActive(ControllerContext controllerContext); // // Summary: // This method is an implementation of System.Web.Mvc.IActionFilter.OnActionExecuted(System.Web.Mvc.ActionExecutedContext) // and supports the ASP.NET MVC infrastructure. It is not intended to be used // directly from your code. // // Parameters: // filterContext: // The filter context. public override void OnActionExecuted(ActionExecutedContext filterContext); // // Summary: // This method is an implementation of System.Web.Mvc.IActionFilter.OnActionExecuting(System.Web.Mvc.ActionExecutingContext) // and supports the ASP.NET MVC infrastructure. It is not intended to be used // directly from your code. // // Parameters: // filterContext: // The filter context. public override void OnActionExecuting(ActionExecutingContext filterContext); // // Summary: // This method is an implementation of System.Web.Mvc.IExceptionFilter.OnException(System.Web.Mvc.ExceptionContext) // and supports the ASP.NET MVC infrastructure. It is not intended to be used // directly from your code. // // Parameters: // filterContext: // The filter context. public void OnException(ExceptionContext filterContext); // // Summary: // This method is an implementation of System.Web.Mvc.IResultFilter.OnResultExecuted(System.Web.Mvc.ResultExecutedContext) // and supports the ASP.NET MVC infrastructure. It is not intended to be used // directly from your code. // // Parameters: // filterContext: // The filter context. public override void OnResultExecuted(ResultExecutedContext filterContext); // // Summary: // Called before the action result executes. // // Parameters: // filterContext: // The filter context, which encapsulates information for using System.Web.Mvc.AuthorizeAttribute. // // Exceptions: // System.ArgumentNullException: // The filterContext parameter is null. public override void OnResultExecuting(ResultExecutingContext filterContext); } }