ASP. NET Cache Technology

Source: Internet
Author: User
Tags configuration settings

1 ASP. NET Cache
(1) Cache Technology Overview
In website applications, website applications can store frequently accessed data and data that requires a large amount of processing time to be created in the memory, thus improving the overall performance of the website. For example, if an application uses complex logic to process a large amount of data and then returns the data as a report that is frequently accessed by the user, it is more efficient to avoid re-creating a report when the user requests data each time. Similarly, if an application contains a page that processes complex data but does not need to be updated frequently, re-creating the page on the server upon each request will result in inefficiency.
Note: To improve application performance, ASP. NET uses two basic caching mechanisms to provide caching functions. The first mechanism is application caching, which allows you to cache generated data, such as dataset or custom Report Business Objects. The second mechanism is the page output cache, which saves the page processing output and reuses the saved output when the user requests the page again, instead of processing the page again.
Page output cache: The page output cache stores the processed ASP. NET page content in the memory. This mechanism allows ASP. NET to send page responses to the client without having to go through the page processing lifecycle again. The page output cache is particularly useful for pages that do not change frequently but require a large amount of processing to be created.
Application cache: The application cache provides a programming method that stores arbitrary data in the memory through key/value pairs. The advantage of using the application cache is that ASP. NET manages the cache, which removes the items in the cache when the items expire, are invalid, or the memory is insufficient. You can also configure the application cache to notify the application when an item is removed.
(2) New cache Functions
Cache configuration file: the cache configuration file can create cache settings in the web. config file of the application, and then reference these settings on a single page. You can apply cache settings to multiple pages at the same time. For example, you can define a cache configuration file, which sets the page cache duration to one day, and then you can configure each page to use this cache configuration file, the cache duration for these pages is one day. If you change a cache configuration file to no cache, these pages will be stopped.
Custom cache dependencies: in ASP. NET 2.0, you can create your own custom cache dependencies based on specific application conditions. To create a custom cache dependency, You need to inherit the class from cachedependency and implement your own dependency method in the Custom class. For example, you can create a dependency to poll data in Web Services. Cache data is invalid when data changes.
Sqlcachedependency: ASP. NET 2.0 introduces the sqlcachedependency class. It can configure an item in the cache so that it can have dependencies on tables or rows in the SQL Server database. When changes occur in a table or a specific row, the cache items with dependencies become invalid and removed from the cache. ASP. NET 2.0 can set table dependencies in SQL Server 7.0, SQL Server 2000, and SQL Server 2005. When using SQL Server 2005, you can also set dependencies for specific records.
Post-cache replacement: ASP. NET 2.0 now supports post-cache replacement, which can disable caching for some configurations on the page. Therefore, even if the page is cached, part of the page will be reprocessed when you request the page again.
(3) cache Configuration
Cache configuration can be implemented in multiple ways, including configuration file configuration, single page configuration, and user control configuration.
Note: configuration file configuration is mainly used to configure page output cache settings in any configuration file of the application configuration hierarchy, including machine. config file or application-specific web. config file.
A single page configuration allows you to set cache options in a declaration or programming mode on a single page. You can also apply the cache configuration file created in the configuration file to a single page. User Control configuration allows you to set cache in a single user control in declarative or programming mode. This is a simple cache Method for page content that is not cached in other cases.
Configuration file configuration: Since the configuration method of the machine. config file is similar to that of the web. config file, this section only describes how to configure the Web. config file to use the cache. In the Web. config file, there are two top-level Configuration sections used for page output cache: outputcachesection and outputcachesettingssection. The outputcachesection section is used to configure the application scope, for example, whether to enable or disable the page output cache. You can add enableoutputcache = "false" to outputcachesection to disable the page output cache for the entire application. Because the settings in the configuration file take precedence over the cache settings on a single page, the sample settings will disable the output cache. Outputcachesettingssection is used to configure the configuration files and dependencies that can be used by a single page. For example, the following code creates an outputcacheprofiles file named cacheprofile1, which will cache the page for 60 seconds:
<Outputcachesettings>
<Outputcacheprofiles>
<Add name = "cacheprofile1" Duration = "60"/>
</Outputcacheprofiles>
</Outputcachesettings>
Page cache configuration settings: You can configure the cache configuration file defined by the application in the configuration file. You can also configure a single cache attribute in the @ outputcache command, or set it by setting the attribute in the class definition on the page.
User Control cache configuration settings: You can configure the user control cache by setting the @ outputcache command in the user control file, or setting the partialcachingattribute attribute in the control class definition.
2 ASP. NET page Cache
ASP. NET can cache partial or all responses generated by ASP. NET pages. in ASP. NET, this technology is called page cache.
Note: The page cache technology includes how to configure the description and programming settings. You can set the cache expiration time on the page and check the validity of the cache page. At the same time, the page cache can cache the version of the page and different parts of the page.
(1) Declare the page Cache
You can declare the page cache in two ways. One is to declare the cache directly on each page, and the other is to define the cache Configuration Attribute in the configuration file, set this attribute on each page.
When declaring the page cache using the method directly declared on the page, you need to include the @ outputcache command in the page and define the duration and varybyparam attributes. The @ outputcache command contains the location attribute and defines its value as one of the following values in the outputcachelocation enumeration: Any, client, downstream, server, serverandclient, or none. The following code demonstrates how to set the page cache to 60 seconds:
<% @ Outputcache duration = "60" varybyparam = "NONE" %>
Another method is to declare a unified cache policy through the configuration file, and then inherit from each page separately. Define the cache configuration file in the application configuration file web. config, which includes the duration and varybyparam settings, as shown in the following code:
<Caching>
<Outputcachesettings>
<Outputcacheprofiles>
<Add name = "demotest" Duration = "30" varybyparam = "NONE"/>
</Outputcacheprofiles>
</Outputcachesettings>
</Caching>
Use the @ outputcache command on each ASP. NET page of the configuration file and set the cacheprofile attribute to the name of the cache configuration file defined in the web. config file:
<% @ Outputcache cacheprofile = "demotest" %>
(2) programming to set page Cache
You can set the page cache by programming. If the application sets the cache at runtime, you can set it by referring to the following programming method. In the code on the page, call the setcacheability method of the cache attribute of the response object.
Response. cache. setcacheability (httpcacheability. Public );
(3) set the page cache expiration time
In ASP. NET, if you want to set the expiration time of the page cache, you can set it through declaration and programming.
Tip: Set the cache expiration time of the page by declaring it. You need to include the @ outputcache command in the ASP. NET page for caching the response. Set the duration attribute to a positive value and the varybyparam attribute to a value.
Tip: You can set the expiration Policy for the page by using the cache attribute of the response object in the background code of the page, as shown in the following code:
Response. cache. setexpires (datetime. Now. addseconds (60 ));
Response. cache. setcacheability (httpcacheability. Public );
Response. cache. setvaliduntilexpires (true );
(4) check the validity of the cache page
When a user requests a cache page, ASP. NET determines whether the cache output is still valid Based on the cache policy defined in the page. If the cache output is valid, the output is sent to the client without reprocessing the page. ASP. NET provides the function of using verification callback to run code during the verification check. You can write custom logic to check whether the page is valid. Verification callback can invalidate cache pages other than normal processes that use cached dependencies. The following example shows how to check the validity of this method:
Protected void page_load (Object sender, eventargs E)
{
// Add callback Cache
Response. cache. addvalidationcallback (New httpcachevalidatehandler (validatecacheoutput), null );
}
Public static void validatecacheoutput (httpcontext context, object data, ref httpvalidationstatus status ){
// Determine whether the request contains a status object
If (context. Request. querystring ["status"]! = NULL ){
// Retrieve the value of the status object
String pagestatus = context. Request. querystring ["status"];
// Determine whether the status value is invalid
If (pagestatus = "invalid ")
Status = httpvalidationstatus. invalid;
// Determine whether the status value is ignore
Else if (pagestatus = "Ignore ")
Status = httpvalidationstatus. ignorethisrequest;
Else
Status = httpvalidationstatus. valid;
}
// If the status value does not exist, the display is incorrect.
Else
Status = httpvalidationstatus. valid;
}
(5) cache page version
In actual development, different versions are created for the page based on the request. For example, the page may have different outputs based on the values passed in the query string. ASP. NET allows multiple versions of the same page to be cached in the output cache. The output cache may vary depending on the following factors: query string in the initial request, control value passed during delivery, HTTP header passed with the request, and the main version number of the browser sending the request.
Tip: You can cache multiple versions output by using the @ outputcache command attribute declaration method or the httpcachepolicy programming method.
@ Outputcache Commands include four attributes that can be used to cache multiple versions output by pages:
The varybyparam attribute can be used to make the cache output result different from the query string. Example:
<% @ Outputcache duration = "60" varybyparam = "param1" %>
The varybycontrol attribute allows the cache to output cache conditions that vary with control values. Example:
<% @ Outputcache duration = "60" varybycontrol = "label1; label2; label3" %>
The varybyheader attribute allows the cache to output cache conditions that vary with the HTTP header of the request. Example:
<% @ Outputcache duration = "60" varybyparam = "NONE" varybyheader = "Accept-language" %>
The varybycustom attribute can be used to cache situations where the livestock vary by browser type or custom string. Example:
<% @ Outputcache duration = "60" varybyparam = "NONE" varybycustom = "Browser" %>
3. cache application data
ASP. NET provides a powerful and easy-to-use cache mechanism for storing objects created by a large number of server resources in the memory. Caching these types of resources will greatly improve the application performance.
Note: The cache is implemented by the cache class, And the cache instance is dedicated to each application. The cache lifetime depends on the lifetime of the application. After the application is restarted, the cache object is created again.
(1) Add cache items
You can add cache items in multiple ways, including:
Add items to the cache by setting keys and values.
Use the insert method to add items to the cache.
Add an item to the cache and add a dependency so that the item is removed from the cache when the dependency item is changed. You can set items based on other cache items, files, and multiple objects.
Add items without an expiration Policy to the cache.
Add items to the cache and define the relative priority of the cached items.
Add an item by calling the add method.
You can add cache items directly by using keys and values. The sample code is as follows:
Cache ["test1"] = "test1 ";
Use the insert method to add cache items to the cache object. The sample code is as follows:
Cache. insert ("Test2", "Test2 ");
Add items to the cache and add dependencies. The sample code is as follows:
String [] dependencies = {"Test2 "};
Cache. insert ("test3", "test3", new system. Web. caching. cachedependency (null, dependencies ));
Add a cache entry with an expiration Policy. The sample code is as follows:
Cache. insert ("test4", "test4", null, datetime. Now. addminutes (1D), system. Web. caching. cache. noslidingexpiration );
Add a cache entry with a priority. The sample code is as follows:
Cache. insert ("test5", "test5", null, system. Web. caching. cache. noabsoluteexpiration,
System. Web. caching. cache. noslidingexpiration, system. Web. caching. cacheitempriority. High, null );
Add cache items by calling the add method. The sample code is as follows:
String test6 = (string) cache. Add ("test6", "test6", null, system. Web. caching. cache. noabsoluteexpiration,
System. Web. caching. cache. noslidingexpiration, system. Web. caching. cache. cacheitempriority. Default, null );
(2) cache item Retrieval
Note: To retrieve cache items from the cache, specify the key for storing the cache items. Because the information stored in the cache is easy to lose, that is, the information may be stored by ASP. therefore, when retrieving a cache item, you must first determine whether the cache item corresponding to the key value exists before searching.
The following code example demonstrates how to determine whether an item named cacheitem is included in the cache. If yes, the code will allocate the content of the item to the variable named cachedstring. If this item is not in the cache, the Code adds it to the cache and assigns it to cachedstring. The sample code is as follows:
String cachedstring;
// Determine whether the cacheitem cache is empty
If (Cache ["cacheitem"]! = NULL)
{
// Obtain the cache content of the cacheitem Value
Cachedstring = (string) cache ["cacheitem"];
}
Else
{
// Add cacheitem cache Value
Cache. insert ("cacheitem", "Hello, world .");
Cachedstring = (string) cache ["cacheitem"];
}
(3) Deletion of cache items
Data in the ASP. NET cache is easy to lose, that is, it cannot be stored permanently. The reason why the cache is automatically removed may be that the cache is full, the cache has expired, or the dependency has changed.
Tip: In addition to automatically removing items from the cache, you can also explicitly remove items. If you want to display a key to delete a cache item of a specified key value, you can call the Remove Method to pass the key of the item to be removed. The sample code is as follows:
Cache. Remove ("test1 ");
4. cache item operation example
The HTML code of the corresponding source view control is as follows:
<% @ Page Language = "C #" autoeventwireup = "true" codefile = "addcache. aspx. cs" inherits = "addcache" %>

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title page </title>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
<Asp: button id = "button1" runat = "server" onclick = "button#click" text = "set cache directly"/> & nbsp; <asp: button
Id = "button8" runat = "server" onclick = "button8_click" text = "Remove"/> <br/>
<Asp: button id = "button2" runat = "server" onclick = "button2_click" text = "insert set cache"/>
<Asp: button id = "button9" runat = "server" onclick = "button9_click" text = "Remove"/> <br/>
<Asp: button id = "button3" runat = "server" onclick = "button3_click" text = "set cache dependencies to other cache items"/>
<Asp: button id = "button10" runat = "server" onclick = "button10_click" text = "Remove"/> <br/>
<Asp: button id = "button4" runat = "server" text = "sets the cache dependency to file" onclick = "button4_click"/> & nbsp; <asp: button
Id = "button11" runat = "server" onclick = "button11_click" text = "Remove"/> <br/>
<Asp: button id = "button6" runat = "server" onclick = "button6_click" text = "add cache with expiration Settings"/> & nbsp; <asp: button
Id = "button12" runat = "server" onclick = "button12_click" text = "Remove"/> <br/>
<Asp: button id = "button5" runat = "server" onclick = "button5_click" text = "add cache entry with priority"/>
<Asp: button id = "button13" runat = "server" onclick = "button13_click" text = "Remove"/> <br/>
<Br/>
<Br/>
<Asp: button id = "button7" runat = "server" onclick = "button7_click" text = ""/>
<Br/>
<Br/>
<Asp: Label id = "label1" runat = "server"> </ASP: Label> </div>
</Form>
</Body>
</Html>
In the background of the page, add events for each button control:
// Directly set the cache button event
Protected void button#click (Object sender, eventargs E)
{
Cache ["mode1"] = "directly set cache ";
}
// Remove this cache button event
Protected void button8_click (Object sender, eventargs E)
{
Cache. Remove ("mode1 ");
}

// Set the cache button event using the insert method
Protected void button2_click (Object sender, eventargs E)
{
Cache. insert ("mode2", "insert sets cache ");
}
// Remove this cache button event
Protected void button9_click (Object sender, eventargs E)
{
Cache. Remove ("mode2 ");
}

// Add the mode2 cache item mode3
Protected void button3_click (Object sender, eventargs E)
{
String [] dependencies = {"mode2 "};
Cache. insert ("mode3", "mode2 ",
New system. Web. caching. cachedependency (null, dependencies ));
}
// Remove this cache button event
Protected void button10_click (Object sender, eventargs E)
{
Cache. Remove ("mode3 ");
}

// Add cache items dependent on the file xmlfile. xml
Protected void button4_click (Object sender, eventargs E)
{
Cache. insert ("mode4", "File Cache dependencies ",
New system. Web. caching. cachedependency (server. mappath ("xmlfile. xml ")));
}
// Remove this cache button event
Protected void button11_click (Object sender, eventargs E)
{
Cache. Remove ("mode4 ");
}

// Set cache items with expiration settings
Protected void button6_click (Object sender, eventargs E)
{
Cache. insert ("mode5", "cache items with expiration time ",
Null, system. Web. caching. cache. noabsoluteexpiration,
New timespan (0, 10, 0 ));
}
// Remove this cache button event
Protected void button12_click (Object sender, eventargs E)
{
Cache. Remove ("mode5 ");
}

// Set cache items with priority
Protected void button5_click (Object sender, eventargs E)
{
Cache. insert ("mode6", "cache items with priority set ",
Null, system. Web. caching. cache. noabsoluteexpiration,
System. Web. caching. cache. noslidingexpiration,
System. Web. caching. cacheitempriority. High, null );
}
// Remove this cache button event
Protected void button13_click (Object sender, eventargs E)
{
Cache. Remove ("mode6 ");
}

// Display all the cached key values on the page
Protected void button7_click (Object sender, eventargs E)
{
Stringbuilder sb = new stringbuilder ();
Idictionaryenumerator cacheenum = cache. getenumerator ();
While (cacheenum. movenext ())
{
SB. append ("cache key --");
SB. append (cacheenum. Key );
SB. append ("cache value --");
SB. append (cacheenum. value );
SB. append ("<br/> ");
}
This. label1.text = sb. tostring ();
}
Because the cached item mode4 depends on an external file xmlfile. XML, so you need to add a file named xmlfile under the website. XML file. When the content of the file is modified, the cache item fails.

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.