緩存是將信息(數據或頁面)放在內存中以免頻繁的數據庫存儲或執行整個頁面的生命週期,直到緩存的信息過時或依賴變動纔再次從數據庫中讀取數據或從新執行頁面的生命週期。在系統優化過程當中,緩存是比較廣泛的優化作法和見效比較快的作法。
MVC緩存本質上仍是.NET的一套緩存體系,只不過該緩存體系應用在了MVC框架上。下面的示例把緩存應用在MVC上。html
緩存的經常使用場景:web
數據被頻繁的使用,而且不多發生變化或對即時性的要求不高。sql
Control緩存便是把緩存應用到整個Control上,該Control下的全部Action都會被緩存起來。Control緩存的粒度比較粗,應用也比較少些。數據庫
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 7 namespace MvcCache.Control.Controllers 8 { 9 [OutputCache(Duration = 10)] 10 public class ControlController : Controller 11 { 12 // 13 // GET: /Home/ 14 public ActionResult Index() 15 { 16 ViewBag.CurrentTime = System.DateTime.Now; 17 return View(); 18 } 19 20 public ActionResult Index1() 21 { 22 ViewBag.CurrentTime = System.DateTime.Now; 23 return View(); 24 } 25 26 } 27 }
在名爲Control的Control中加入了OutputCache,並設置持續時間爲10秒(Duration=10),即每10秒後過時當再次觸發時更新緩存。下面是View中的代碼,打印ViewBag的時間。api
1 @{ 2 ViewBag.Title = "Index"; 3 } 4 5 <h2>@ViewBag.CurrentTime</h2> 6 7 @{ 8 ViewBag.Title = "Index1"; 9 } 10 11 <h2>@ViewBag.CurrentTime</h2>
即把緩存用到Action上,Action緩存爲比較經常使用的緩存方式,該方式粒度細一些。使用方法相似Control緩存。瀏覽器
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 7 namespace MvcCache.Control.Controllers 8 { 9 //Control不加緩存 10 public class ActionController : Controller 11 { 12 //該Index的Action加緩存 13 [OutputCache(Duration = 10)] 14 public ActionResult Index() 15 { 16 ViewBag.CurrentTime = System.DateTime.Now; 17 return View(); 18 } 19 20 //該Action不加緩存 21 public ActionResult Index1() 22 { 23 ViewBag.CurrentTime = System.DateTime.Now; 24 return View(); 25 } 26 27 } 28 }
Index加入了緩存,而Index1沒有加。此時Index1每次刷新頁面都會取到當前的時間並打印。緩存
1 @{ 2 ViewBag.Title = "Index"; 3 4 } 5 6 <h2>@ViewBag.CurrentTime</h2> 7 8 @{ 9 ViewBag.Title = "Index1"; 10 } 11 12 <h2>@ViewBag.CurrentTime</h2>
當咱們須要將N個Control或Action加入緩存,而且緩存的參數是一致的狀況下,咱們能夠把相關的設置放到Web.config中,並在程序中加入相應的配置。服務器
1 <?xml version="1.0" encoding="utf-8"?> 2 <!-- 3 For more information on how to configure your ASP.NET application, please visit 4 http://go.microsoft.com/fwlink/?LinkId=169433 5 --> 6 7 <configuration> 8 <appSettings> 9 <add key="webpages:Version" value="2.0.0.0" /> 10 <add key="webpages:Enabled" value="false" /> 11 <add key="PreserveLoginUrl" value="true" /> 12 <add key="ClientValidationEnabled" value="true" /> 13 <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 14 </appSettings> 15 <system.web> 16 <!--配置緩存--> 17 <caching> 18 <outputCacheSettings> 19 <outputCacheProfiles> 20 <add name="TestConfigCache" duration="10"/> 21 </outputCacheProfiles> 22 </outputCacheSettings> 23 </caching> 24 <!--配置緩存--> 25 <httpRuntime targetFramework="4.5" /> 26 <compilation debug="true" targetFramework="4.5" /> 27 <pages> 28 <namespaces> 29 <add namespace="System.Web.Helpers" /> 30 <add namespace="System.Web.Mvc" /> 31 <add namespace="System.Web.Mvc.Ajax" /> 32 <add namespace="System.Web.Mvc.Html" /> 33 <add namespace="System.Web.Routing" /> 34 <add namespace="System.Web.WebPages" /> 35 </namespaces> 36 </pages> 37 </system.web> 38 <system.webServer> 39 <validation validateIntegratedModeConfiguration="false" /> 40 41 <handlers> 42 <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> 43 <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> 44 <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 45 <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" /> 46 <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" /> 47 <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" /> 48 </handlers> 49 </system.webServer> 50 51 </configuration>
配置緩存節只須要將其放在system.web節下便可,下面是使用的方法mvc
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 7 namespace MvcCache.Control.Controllers 8 { 9 public class ConfigController : Controller 10 { 11 //TestConfigCache爲在配置文件中配置的緩存節 12 [OutputCache(CacheProfile = "TestConfigCache")] 13 public ActionResult Index() 14 { 15 ViewBag.CurrentTime = System.DateTime.Now; 16 return View(); 17 } 18 19 } 20 }
注:當Control與Action都應用了緩存時,以Action的緩存爲主。app
下面代碼爲mvc4的OutputCache的定義,因爲使用的是英文版本IDE和框架,所以註釋所有爲英文。後面的講解主要講解經常使用的屬性,對於緩存依賴這個重點內容在下面單獨講解使用方法。
若是想了解各個屬性的詳細說明及使用請查閱MSDN,連接地址以下:https://msdn.microsoft.com/zh-cn/library/system.web.mvc.outputcacheattribute.aspx
1 using System; 2 using System.Web.UI; 3 4 namespace System.Web.Mvc 5 { 6 // Summary: 7 // Represents an attribute that is used to mark an action method whose output 8 // will be cached. 9 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] 10 public class OutputCacheAttribute : ActionFilterAttribute, IExceptionFilter 11 { 12 // Summary: 13 // Initializes a new instance of the System.Web.Mvc.OutputCacheAttribute class. 14 public OutputCacheAttribute(); 15 16 // Summary: 17 // Gets or sets the cache profile name. 18 // 19 // Returns: 20 // The cache profile name. 21 public string CacheProfile { get; set; } 22 // 23 // Summary: 24 // Gets or sets the child action cache. 25 // 26 // Returns: 27 // The child action cache. 28 public static System.Runtime.Caching.ObjectCache ChildActionCache { get; set; } 29 // 30 // Summary: 31 // Gets or sets the cache duration, in seconds. 32 // 33 // Returns: 34 // The cache duration. 35 public int Duration { get; set; } 36 // 37 // Summary: 38 // Gets or sets the location. 39 // 40 // Returns: 41 // The location. 42 public OutputCacheLocation Location { get; set; } 43 // 44 // Summary: 45 // Gets or sets a value that indicates whether to store the cache. 46 // 47 // Returns: 48 // true if the cache should be stored; otherwise, false. 49 public bool NoStore { get; set; } 50 // 51 // Summary: 52 // Gets or sets the SQL dependency. 53 // 54 // Returns: 55 // The SQL dependency. 56 public string SqlDependency { get; set; } 57 // 58 // Summary: 59 // Gets or sets the vary-by-content encoding. 60 // 61 // Returns: 62 // The vary-by-content encoding. 63 public string VaryByContentEncoding { get; set; } 64 // 65 // Summary: 66 // Gets or sets the vary-by-custom value. 67 // 68 // Returns: 69 // The vary-by-custom value. 70 public string VaryByCustom { get; set; } 71 // 72 // Summary: 73 // Gets or sets the vary-by-header value. 74 // 75 // Returns: 76 // The vary-by-header value. 77 public string VaryByHeader { get; set; } 78 // 79 // Summary: 80 // Gets or sets the vary-by-param value. 81 // 82 // Returns: 83 // The vary-by-param value. 84 public string VaryByParam { get; set; } 85 86 // Summary: 87 // Returns a value that indicates whether a child action cache is active. 88 // 89 // Parameters: 90 // controllerContext: 91 // The controller context. 92 // 93 // Returns: 94 // true if the child action cache is active; otherwise, false. 95 public static bool IsChildActionCacheActive(ControllerContext controllerContext); 96 // 97 // Summary: 98 // This method is an implementation of System.Web.Mvc.IActionFilter.OnActionExecuted(System.Web.Mvc.ActionExecutedContext) 99 // and supports the ASP.NET MVC infrastructure. It is not intended to be used 100 // directly from your code. 101 // 102 // Parameters: 103 // filterContext: 104 // The filter context. 105 public override void OnActionExecuted(ActionExecutedContext filterContext); 106 // 107 // Summary: 108 // This method is an implementation of System.Web.Mvc.IActionFilter.OnActionExecuting(System.Web.Mvc.ActionExecutingContext) 109 // and supports the ASP.NET MVC infrastructure. It is not intended to be used 110 // directly from your code. 111 // 112 // Parameters: 113 // filterContext: 114 // The filter context. 115 public override void OnActionExecuting(ActionExecutingContext filterContext); 116 // 117 // Summary: 118 // This method is an implementation of System.Web.Mvc.IExceptionFilter.OnException(System.Web.Mvc.ExceptionContext) 119 // and supports the ASP.NET MVC infrastructure. It is not intended to be used 120 // directly from your code. 121 // 122 // Parameters: 123 // filterContext: 124 // The filter context. 125 public void OnException(ExceptionContext filterContext); 126 // 127 // Summary: 128 // This method is an implementation of System.Web.Mvc.IResultFilter.OnResultExecuted(System.Web.Mvc.ResultExecutedContext) 129 // and supports the ASP.NET MVC infrastructure. It is not intended to be used 130 // directly from your code. 131 // 132 // Parameters: 133 // filterContext: 134 // The filter context. 135 public override void OnResultExecuted(ResultExecutedContext filterContext); 136 // 137 // Summary: 138 // Called before the action result executes. 139 // 140 // Parameters: 141 // filterContext: 142 // The filter context, which encapsulates information for using System.Web.Mvc.AuthorizeAttribute. 143 // 144 // Exceptions: 145 // System.ArgumentNullException: 146 // The filterContext parameter is null. 147 public override void OnResultExecuting(ResultExecutingContext filterContext); 148 } 149 }
經常使用屬性:
1)CacheProfile:緩存使用的配置文件的緩存名稱。
2)Duration:緩存時間,以秒爲單位,這個除非你的Location=None,能夠不添加此屬性,其他時候都是必須的。
3)OutputCacheLocation:枚舉類型,緩存的位置。當設置成None時,全部緩存將失效,默認爲Any。
Any:頁面被緩存在瀏覽器、代理服務器端和web服務器端;
Client:緩存在瀏覽器;
DownStream:頁面被緩存在瀏覽器和任何的代理服務器端;
Server:頁面被緩存在Web服務器端;
None:頁面不緩存;
ServerAndClient:頁面被緩存在瀏覽器和web服務器端;
4)VaryByParam:用於多個輸出緩存的字符串列表,並以分號進行分隔。默認時,該字符串與GET方法傳遞的參數或與POST方法傳遞的變量相對應。當被設置爲多個參數時,輸出緩存將會爲每一個參數都準備一個與之相對應的文檔版本。可能值包括none,*,以及任何有效的查詢串或POST參數名稱。
若是您不想要爲不一樣的已緩存內容指定參數,能夠將其設置爲none。若是想要指定全部的已緩存內容參數,能夠設置爲*。
SqlDependency:一個值,用於標識操做的輸出緩存所依賴的一組數據庫名稱和表名稱對。SqlCacheDependency 類在全部受支持的 SQL Server 版本 (7.0, 2000, 2005) 上監視特定的 SQL Server 數據庫表,數據庫表發生更改時,將自動刪除緩存項,並向 Cache 中添加新版本的項。
概念理解起來很簡單,主要是如何應用。下面爲應用實例。示例說明:數據庫爲本地數據庫,庫名:wcfDemo(寫wcf教程時用的庫,懶了,直接用了),監聽表名:user。緩存時間爲:3600秒即一小時。數據庫依賴週期爲500毫秒,即每0.5秒監聽下數據庫是否有變化,若是有變化則當即更新緩存。
第一步:創建Control,測試代碼以下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.Mvc; 6 7 namespace MvcCache.Control.Controllers 8 { 9 public class SqlDependencyController : Controller 10 { 11 [OutputCache(CacheProfile = "SqlDependencyCache")] 12 public ActionResult Index() 13 { 14 ViewBag.CurrentTime = System.DateTime.Now; 15 return View(); 16 } 17 18 } 19 }
第二步,在配置文件中配置CacheProfile爲SqlDependencyCache的節,而且配置緩存對數據庫的依賴。
1 <?xml version="1.0" encoding="utf-8"?> 2 <!-- 3 For more information on how to configure your ASP.NET application, please visit 4 http://go.microsoft.com/fwlink/?LinkId=169433 5 --> 6 7 <configuration> 8 <!--數據庫鏈接字符串--> 9 <connectionStrings> 10 <add name="Conn" connectionString="server=localhost;database=wcfDemo;uid=sa;pwd=123456;" providerName="System.Data.SqlClient"/> 11 </connectionStrings> 12 <!--數據庫鏈接字符串--> 13 <appSettings> 14 <add key="webpages:Version" value="2.0.0.0" /> 15 <add key="webpages:Enabled" value="false" /> 16 <add key="PreserveLoginUrl" value="true" /> 17 <add key="ClientValidationEnabled" value="true" /> 18 <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 19 </appSettings> 20 <system.web> 21 <!--配置緩存--> 22 <caching> 23 <sqlCacheDependency><!--緩存的數據庫依賴節--> 24 <databases> 25 <add name="UserCacheDependency" connectionStringName="Conn" pollTime="500"/><!--Conn:數據庫鏈接字符串的名稱,name隨便啓名,緩存節會用到--> 26 </databases> 27 </sqlCacheDependency> 28 <outputCacheSettings> 29 <outputCacheProfiles> 30 <add name="SqlDependencyCache" duration="3600" sqlDependency="UserCacheDependency:user"/><!--UserCacheDependency:數據庫依賴配置節的名稱,user:數據庫中須要監聽的表名稱--> 31 </outputCacheProfiles> 32 </outputCacheSettings> 33 </caching> 34 <!--配置緩存--> 35 <httpRuntime targetFramework="4.5" /> 36 <compilation debug="true" targetFramework="4.5" /> 37 <pages> 38 <namespaces> 39 <add namespace="System.Web.Helpers" /> 40 <add namespace="System.Web.Mvc" /> 41 <add namespace="System.Web.Mvc.Ajax" /> 42 <add namespace="System.Web.Mvc.Html" /> 43 <add namespace="System.Web.Routing" /> 44 <add namespace="System.Web.WebPages" /> 45 </namespaces> 46 </pages> 47 </system.web> 48 <system.webServer> 49 <validation validateIntegratedModeConfiguration="false" /> 50 51 <handlers> 52 <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> 53 <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> 54 <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 55 <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" /> 56 <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" /> 57 <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" /> 58 </handlers> 59 </system.webServer> 60 61 </configuration>
注意:
1)因爲是緩存對數據庫的依賴,此外必須包含connectionStrings的節。
2)<add name="UserCacheDependency" connectionStringName="Conn" pollTime="500"/>
connectionStringName:數據庫鏈接字符串的名稱
pollTime:監聽數據庫變化的週期,以毫秒爲單位。即每500毫秒查看下數據庫是否有變化。
3)<add name="SqlDependencyCache" duration="3600" sqlDependency="UserCacheDependency:user"/>
sqlDependency:數據依賴的節的名稱+冒號+數據表名稱(小寫)。若是這個依賴會用到多個表,則用分號間隔開,以下所示UserCacheDependency:user;UserCacheDependency:user1
第三步:啓用該數據庫表的緩存依賴通知功能
打開vs命令工具行,輸入:aspnet_regsql -S localhost -U sa -P 123456 -ed -d wcfDemo -et -t user
-S localhost:數據庫地址
-U sa:數據庫登陸名
-P 123456:數據庫登陸密碼
-d wcfDemo:數據庫的名稱
-t user:表名稱(小寫)
由於只是監聽是否發生數據變化,所以表結構隨意,下面的個人表結構:
第四步:測試程序,上面的例子只打印了當前時間,若是不加入緩存依賴的狀況下,1小時以內都應該運行出的結果都是當前時間,每次Ctrl+F5強制刷新瀏覽器時不發生任務變化。當加入緩存依賴後,只要對數據庫的數據進行任意修改都會更新緩存的時間,即更改數據後再刷新瀏覽器時會看到時間在變化。
8.無廢話MVC入門教程八[MvcPager分頁控件的使用]