MVC cache and mvc cache Reprinting

Source: Internet
Author: User

MVC cache (reprinted) and mvc cache reprinted

Address: http://www.cnblogs.com/iamlilinfeng/p/4419362.html

 

1. Introduction to MVC Cache

Cache stores information (data or pages) in the memory to avoid frequent database storage or execution of the entire page lifecycle, it is not until the cached information expires or the dependency is changed that the data is read from the database again or the page lifecycle is re-executed. In the process of system optimization, caching is a common optimization practice and quick action.
The MVC cache is essentially a cache system of. NET, but the cache system is applied to the MVC framework. The following example applies the cache to MVC.

Common cache scenarios:

Data is frequently used and rarely changed or has low requirements for Instant Processing.

Ii. Control Cache

The Control cache applies the cache to the entire Control, and all actions under the Control will be cached. The Control cache is coarse-grained and has fewer applications.

 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 : Controller11     {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 }

The OutputCache is added to the Control with the name "Control" and the Duration is set to 10 seconds (Duration = 10). That is, the cache is updated every 10 seconds after expiration when it is triggered again. The following is the code in the View to print the ViewBag time.

 1 @{ 2     ViewBag.Title = "Index"; 3 } 4  5 

Iii. Action caching

That is, the cache is used on the Action, and the Action cache is a common cache method, which has a finer granularity. The usage is similar to the Control cache.

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 without caching 10 public class ActionController: Controller11 {12 // Action of this Index with caching 13 [OutputCache (Duration = 10)] 14 public ActionResult Index () 15 {16 ViewBag. currentTime = System. dateTime. now; 17 return View (); 18} 19 20 // this Action is not cached 21 public ActionResult Index1 () 22 {23 ViewBag. currentTime = System. dateTime. now; 24 return View (); 25} 26 27} 28}

Index is added to the cache, but Index1 is not added. At this time, each time the Index1 refreshes the page, the current time is obtained and printed.

 1 @{ 2     ViewBag.Title = "Index"; 3   4 } 5  6 

4. Use the configuration file

When we need to add N controls or actions to the cache and the cached parameters are consistent, we can put the relevant settings on the Web. config, and add the corresponding configuration in the program.

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 <! -- Configure cache --> 17 <caching> 18 <outputCacheSettings> 19 <outputCacheProfiles> 20 <add name = "TestConfigCache" duration = "10"/> 21 </outputCacheProfiles> 22 </ outputCacheSettings> 23 </caching> 24 <! -- Configure cache --> 25 

To configure the cache section, you only need to put it under the system. web Section. The following is the method used:

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: Controller10 {11 // TestConfigCache is the cache section 12 configured in the configuration file [OutputCache (CacheProfile = "TestConfigCache")] 13 public ActionResult Index () 14 {15 ViewBag. currentTime = System. dateTime. now; 16 return View (); 17} 18 19} 20}

Note: When both Control and Action are applied to the cache, the Action cache is the main factor.

V. Introduction to OutputCache Parameters

The following code defines the OutputCache of mvc4. Because the English version of IDE and framework is used, all annotations are in English. The subsequent explanations mainly explain common attributes. The important content of cache dependency is described separately below.

For details and use of each attribute, see MSDN. Link: 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 used100         //     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 used110         //     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 used120         //     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 used130         //     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 }

Common attributes:
1) CacheProfile: cache name of the configuration file used for caching.

2) Duration: the cache time, in seconds. This attribute can be left empty unless your Location is set to None. It is required in other cases.

3) OutputCacheLocation: Enumeration type, cache location. When it is set to None, all caches will become invalid. The default value is Any.

Any: the page is cached on the browser, proxy server, and web server;

Client: cached in the browser;

DownStream: the page is cached in the browser and any proxy server;

Server: the page is cached on the Web Server;

None: the page is not cached;

ServerAndClient: the page is cached on the browser and web server;

4) VaryByParam: A list of multiple output cache strings separated by semicolons. By default, this string corresponds to the parameters passed by the GET method or to the variables passed by the POST method. When multiple parameters are set, the output cache prepares a document version corresponding to each parameter. Possible values include none, *, and any valid query string or POST parameter names.

If you do not want to specify parameters for different cached content, you can set them to none. If you want to specify all cached content parameters, you can set them *.

Vi. cache dependency

SqlDependency: A value used to identify a group of database names and table name pairs that the Operation's output cache depends on. The SqlCacheDependency class monitors specific SQL Server database tables on all supported SQL Server versions (7.0, 2000,200 5). When database tables are changed, the cache items are automatically deleted, add new items to the Cache.

The concept is easy to understand and mainly involves how to apply it. The following is an application instance. Example Description: the database is a local database. The database name is wcfDemo (the database used for writing the wcf tutorial. It is too lazy and used directly). The listening table name is user. The cache time is 3600 seconds, that is, one hour. The database dependency cycle is 500 milliseconds, that is, whether the database changes under the monitoring every 0.5 seconds. If there is any change, the cache is updated immediately.

Step 1: Create a Control. The test code is as follows:

 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 : Controller10     {11         [OutputCache(CacheProfile = "SqlDependencyCache")]12         public ActionResult Index()13         {14             ViewBag.CurrentTime = System.DateTime.Now;15             return View();16         }17 18     }19 }

Step 2: configure the CacheProfile as SqlDependencyCache section in the configuration file and configure the cache dependency on the database.

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 <! -- Database connection string --> 9 <connectionStrings> 10 <add name = "Conn" connectionString = "server = localhost; database = wcfDemo; uid = sa; pwd = 123456; "providerName =" System. data. sqlClient "/> 11 </connectionStrings> 12 <! -- Database connection string --> 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 <! -- Configure cache --> 22 <caching> 23 <sqlCacheDependency> <! -- Cache database dependency section --> 24 <databases> 25 <add name = "UserCacheDependency" connectionStringName = "Conn" pollTime = "500"/> <! -- Conn: the name of the database connection string, in the cache section, --> 26 </databases> 27 </sqlCacheDependency> 28 <outputcachesetency> 29 <outputCacheProfiles> 30 <add name = "SqlDependencyCache" duration = "3600" sqlDependency = "UserCacheDependency: user "/> <! -- UserCacheDependency: name of the database dependency configuration section. user: name of the table to be monitored in the database --> 31 </outputCacheProfiles> 32 </outputCacheSettings> 33 </caching> 34 <! -- Configure cache --> 35 

Note:
1) because it is a cache-dependent database, it must also contain the connectionStrings section.

2) <add name = "UserCacheDependency" connectionStringName = "Conn" pollTime = "500"/>

ConnectionStringName: name of the database connection string

PollTime: The period in milliseconds for monitoring database changes. Check whether the database changes every 500 milliseconds.

3) <add name = "SqlDependencyCache" duration = "3600" sqlDependency = "UserCacheDependency: user"/>

SqlDependency: name of the data dependency section + colon + data table name (lower case ). If this dependency uses multiple tables, separate them with semicolons, as shown in the following figure: UserCacheDependency: user; UserCacheDependency: user1

Step 3: Enable the cache dependency notification function for the database table

Open the vs command line and enter: aspnet_regsql-S localhost-U sa-P 123456-ed-d wcfDemo-et-t user

-S localhost: Database address

-U sa: Database Login Name

-P 123456: Database logon Password

-D wcfDemo: Database Name

-T user: Table Name (lower case)

The table structure is as follows:

Step 4: test the program. The above example only prints the current time. If no cache dependency is added, all the results that should be run within one hour are the current time, the task does not change every time Ctrl + F5 force refresh the browser. After the cache dependency is added, the cache time will be updated as long as any modification is made to the database data. That is, when the data is changed and the browser is refreshed, the time is changing.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.