ASP. NET: Cache Usage

Source: Internet
Author: User

When it comes to ASP. NET cache, it is: cache as soon as possible; you should cache frequently in applicationsProgramEach layer. Add cache support to the data layer, business logic layer, UI, or output layer. Memory is currently very cheap-therefore, implementing caching in the entire application in a smart way can greatly improve performance. Caching can mask many errors. caching is a way to achieve "good enough" performance without having to spend a lot of time and analysis.

The memory is very cheap now, so if you try to optimize it by caching the output for 30 seconds instead of spending a whole day or even a weekCodeOr the database can obtain the required performance, and you will definitely select the cache solution (assuming you can accept 30 seconds of old data ). Cache is one of the features that get a 20% return Using 80%. Therefore, to improve performance, you should first think of cache.

However, if the design is poor, it may lead to adverse consequences. Therefore, you should, of course, try to design the application correctly. However, if you only need to obtain high performance immediately, the cache is your best choice. You can redesign the application as soon as you have time. The page-level output cache is the simplest form of cache. The output cache only retains the HTML copies sent in response to the request in the memory. When there are other requests, the cache output will be provided until the cache expires. In this way, performance may be greatly improved (depending on the overhead required to create the original page output-the output of the sending cache is always fast and stable ). To implement the page output cache, you only need to add an outputcache command to the page.

 

<%@ Outputcache duration = "60" varybyparam = "*" %>

 

Like other page commands, this command should appear at the top of the ASPX page, that is, before any output. It supports five attributes (or parameters), two of which are required. Duration Required attribute. The time when the page should be cached, in seconds. Must be a positive integer. Location specifies the location where the output should be cached. To specify this parameter, it must be any, client, downstream, none, server, or serverandclient. Required attribute of varybyparam. The name of the variable in the request. These variable names should generate separate cache entries ." "None" indicates no change ." * "Can be used to create a cache entry for each variable group. Variables are separated. Varybyheader changes cache entries based on changes in the specified header.

Varybycustom allows you to specify custom changes (for example, "Browser") in global. asax "). The combination of the required duration and varybyparam options can be used to handle most cases. For example, if your product directory allows users to view the directory Page Based on categoryid and page variables, you can set the parameter value to "categoryid; page "varybyparam caches the product directory for a period of time (if the product is not changed at any time, one hour is acceptable, so the duration is 3600 seconds ). This creates separate cache entries for each directory page of each category. Each entry is counted from its first request for one hour. Varybyheader and varybycustom are mainly used to customize the appearance or content of the page based on the client accessing the page. The same URL may need to be rendered and output for both the browser and mobile client. Therefore, different content versions must be cached for different clients.

Alternatively, the page may have been optimized for IE, but it must be completely optimized for Netscape or opera (not just to destroy the page ). The next example is very common. We will provide an example to illustrate how to achieve this goal: Example: varybycustom is used to support browser customization so that each browser has a separate cache entry, the value of varybycustom can be set to "Browser ". This function has been built into the cache module and will insert a separate page Cache version for each browser name and major version.

 

<%@ Outputcache duration = "60" varybyparam = "NONE" varybycustom = "Browser" %>

 

Fragment Caching: the user control outputs the cache and caches the entire page. This is usually not feasible because some parts of the page are customized for users. However, the rest of the page is shared by the entire application. These parts are most suitable for cache using fragment caching and user controls. Menu and other layout elements, especially those dynamically generated from the data source, should also be cached in this way. If necessary, you can configure the Cache control to be changed based on changes to its control (or other attributes) or any other changes supported by the page-level output cache. Using hundreds of pages of the same control group can also share the cache entries of those controls, rather than retaining a separate Cache version for each page. The syntax used to implement fragment caching is the same as that used for page-level output caching, but it is applied to user controls (. ascx files) instead of web forms (. aspx files ). In addition to the location attribute, user controls also support all attributes supported by outputcache on web forms. The user control also supports the outputcache attribute named varybycontrol, which changes the control's cache according to the value of the user control (usually the control on the page, for example, dropdownlist) member.

If varybycontrol is specified, You can omit varybyparam. Finally, by default, each user control on each page is cached separately. However, if a user control does not change with the page in the application and the same name is used on all pages, you can apply the "shared =" true "parameter, this parameter allows the cached version of the user control to be used by all pages that reference the control. Example

 

<%@ Outputcache duration = "60" varybyparam = "*" %>

 

In this example, the ASP. NET user control is cached for 60 seconds, and a separate cache entry is created for each change of the query string and for each page where the control is located.

 

<%@ Outputcache duration = "60" varybyparam = "NONE" varybycontrol = "categorydropdownlist" %>

 

In this example, the ASP. NET user control is cached for 60 seconds, and a separate cache entry is created for each different value of the categorydropdownlist control and for each page where the control is located.

 

<%@ Outputcache duration = "60" varybyparam = "NONE" varybycustom = "Browser" shared = "true %>

 

Finally, this example caches the ASP. Net user control for 60 seconds and creates a cache entry for each browser name and major version. Then, the cache entries of Each browser will be shared by all pages that reference this user control (as long as all pages reference this control with the same ID ). Page-level and user control-level output cache is indeed a way to quickly and easily improve site performance, but ASP. the true flexibility and powerful functions of the net cache are provided by the cache object. With cache objects, you can store any serializable Data Objects and control the expiration method of cache entries based on the combination of one or more dependencies. These dependencies can include the time since the item was cached, the time since the item was last accessed, changes to files and/or folders, and changes to other cache items, after slight processing, you can also include changes to specific tables in the database.

 

//**************************

 

ASP. NET output Cache
Cache is the most important indicator for high-performance and scalable Web applications. ASP. NET provides a high-performance web application caching function. ASP. NET has three caches available for Web applications:
· Output cache, which caches the dynamic response generated by the request.
· Fragment cache: It caches the parts of the response generated by the request.
· Data cache: It caches arbitrary objects programmatically. To support such caching, ASP. NET provides a full-featured caching engine that allows programmers to easily retain data between requests.
Page output cache is very useful. Among the massive access sites, some pages are frequently accessed, which reduces the burden on the system even if the output cache is used for these pages for a small amount of time, because the subsequent requests to these pages will not execute the code to create the page.
However, this is not flexible enough, and there may be a lot of page requests. However, We cache everything on the page, whether it is a high construction cost or a low construction cost. Can there be data that can cache part of the page? Fortunately, ASP. NET provides the ability to create or customize parts of the page for each request. For example, we can cache fragments of user controls with high construction costs on the page.
ASP. NET cache supports file and cache key dependencies, allowing developers to make cache items dependent on external files or other cache items. This technique can be used to invalidate an item when its basic data source is changed. ASP. NET can store these items on Web servers or other software in the request stream, such as a proxy server or browser. This prevents you from re-creating information that meets previous requests, especially information that requires a large amount of processor time or other resources when being created on the server.
Page cache settings for petshop
We can use a low-level outputcache API or a high-level @ outputcache command to implement the page output cache. After the output cache is enabled, an output cache item is created when the first GET request to the page is sent. Subsequent get or head requests are provided by the output cache service until the cache request expires. The output cache also supports cached get or post name/value pairs.
The output cache follows the page expiration and validity policies. If a page is in the output cache and has an expiration policy flag indicating that the page expires 60 minutes after the cache, the page will be removed from the output cache 60 minutes later. If another request is received later, the page code is executed and the page can be cached again.
The following command activates the output cache when the response is received:
<% @ Outputcache duration = "60" varybyparam = "NONE" %>
Duration and varybyparam are mandatory parameters. The former identifies the expiration time, and the latter indicates a string of get or post name/value pairs. If this attribute is not used, it is set to none. Here we also need to describe a parameter varybycustom. Using this parameter, we can customize any text required by the output cache. Besides declaring this attribute in the outputcache Command, we have to rewrite the getvarybycustomstring method in the Code declaration block of the global. asax file of the application to specify the output cache behavior for the custom string.
For example:
<% @ Outputcache varybyparam = "NONE" varybycustom = "categorypagekey" location = "server" Duration = "43200" %>
Here, varybycustom is defined as categorypagekey. In Global. asax, we must define the categorypagekey character to create and output the cache behavior. See the following code.
Public override string getvarybycustomstring (httpcontext context, string Arg ){
String cachekey = "";
Switch (ARG ){
Case "categorypagekey ":
If (request. isauthenticated = true ){
Cachekey = "qqq" + context. Request. querystring ["category_id"] + context. Request. querystring ["requestedpage"];
}
Else {
Cachekey = "AAA" + context. Request. querystring ["category_id"] + context. Request. querystring ["requestedpage"];
}
Break;
Case "searchpagekey ":
If (request. isauthenticated = true ){
Cachekey = "qqq" + context. Request. querystring ["search_text"] + context. Request. querystring ["requestedpage"];
}
Else {
Cachekey = "AAA" + context. Request. querystring ["search_text"] + context. Request. querystring ["requestedpage"];
}
Break;
Case "productpagekey ":
If (request. isauthenticated = true ){
Cachekey = "qqq" + context. Request. querystring ["name"] + context. Request. querystring ["product_id"] + context. Request. querystring ["requestedpage"];
}
Else {
Cachekey = "AAA" + context. Request. querystring ["name"] + context. Request. querystring ["product_id"] + context. Request. querystring ["requestedpage"];
}
Break;
Case "productdetailspagekey ":
If (request. isauthenticated = true ){
Cachekey = "qqq" + context. Request. querystring ["item_id"] + context. Request. querystring ["requestedpage"];
}
Else {
Cachekey = "AAA" + context. Request. querystring ["item_id"] + context. Request. querystring ["requestedpage"];
}
Break;
Case "userid ":
If (request. isauthenticated = true ){
Cachekey = "userid_in ";
}
Else {
Cachekey = "userid_out ";
}
Break;
}
Return cachekey;
}
Based on the actions created by the categorypagekey character, when our request page contains a request for a data page displayed on a specific category_id, cache the call (the page is already cached ).
The following table lists the output cache settings of petshop web applications.
ASP. NET webforms cache setting duration
Controlheader <% @ outputcache
Duration = "43200"
Varybyparam = "NONE"
Varybycustom = "userid" %> 12 hours
Default <% @ outputcache
Duration = "43200"
Varybyparam = "NONE"
Varybycustom = "userid" %> 12 hours
Help <% @ outputcache
Duration = "43200"
Varybyparam = "NONE"
Varybycustom = "userid" %> 12 hours
Category <% @ outputcache
Duration = "43200"
Varybyparam = "NONE"
Varybycustom = "categorypagekey" %> 12 hours
Product <% @ outputcache
Duration = "43200"
Varybyparam = "NONE"
Varybycustom = "productpagekey" %> 12 hours
Productdetails <% @ outputcache
Duration = "43200"
Varybyparam = "NONE"
Varybycustom = "productdetailspagekey" %> 12 hours
Search <% @ outputcache
Duration = "43200"
Varybyparam = "NONE"
Varybycustom = "searchpagekey" %> 12 hours

Obviously, the controlheader at the top of the web page of petshop is related to the user's login status, so it sets the varybycustom attribute to identify the Cache version of the user's different login status. However, because the category page may be accessed in large quantities and the data volume is large, it is necessary to cache the page. However, due to the randomness of the data, different versions exist, for example, for different categories of category, or even data pages displayed on different pages, the varybycustom attribute is used here to cache pages of different versions.
Petshop segment Cache
As mentioned above, ASP. NET can provide partial page data cache, which is usually a costly part of the structure, such as user controls. In petshop, a large number of user controls (especially.. Net sample program duwamish7.0 uses more user controls, and those pages are assembled by controls.) The cache setting method of user controls is basically the same as that of the ASPX page, we will not list them here. Only the controlheader control uses the cache settings.

 

 

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.