Summary of ASP. NET Cache

Source: Internet
Author: User
The best and fastest way to improve performance is, of course, to improve performance through caching. Any web developer should make good use of caching. The cache mechanism in Asp.net is very powerful. Using the cache mechanism can greatly improve the performance of Web applications. The following are some summary of the cache knowledge points to share with you:

1. Page Cache

To implement the page output cache, you only need to add an outputcache command to the page.

<% @ OutputcacheCacheprofile= ""Nostore ="True | false"Duration= "# Ofseconds"Shared= "True | false"Location= "Any | client | downstream | Server | none | serverandclient"Sqldependency= "Database/table name pair | commandnotification"Varybycontrol= "Controlname"Varybycustom= "Browser | customstring"Varybyheader= "Headers"Varybyparam= "Parametername" %>

Cacheprofile

Defines the name of the cache settings associated with this page. Is an optional attribute. The default value is null (""). Note that the @ outputcache command in the user control does not support this attribute. When this attribute is specified on the page, the attribute value must match the name of an available item in the outputcacheprofiles element in the <outputcachesetfiles> Configuration section of the web. config file. If the name does not match the configuration file, an exception is thrown.

Nostore

This attribute defines a Boolean value to determine whether to block secondary storage of sensitive information. Note that the @ outputcache command in the user control does not support this attribute. Setting this attribute to true is equivalent to executing the code "response. cache. setnostore ();" during the request ();".

Duration

Used to set the cache time for pages or user controls. The Unit is seconds. By setting this attribute, you can create an expiration Policy for the HTTP response from the object and automatically cache the page or user control output. Note that the duration attribute is required. Otherwise, the analyzer error may occur.

Shared

This attribute defines a Boolean value to determine whether the output of a user control can be shared by multiple pages. The default value is false. Note that the @ outputcache Command included in the ASP. NET page does not support this attribute.

Location

Specifies the location of the output cache. Its Attribute values are outputcachelocation enumeration values, which are any, client, downstream, none, server, and serverandclient. The default value is any, indicating that the output cache can be used for all requests, including the client browser, proxy server, or server that processes the request. Note that the @ outputcache command in the user control does not support this attribute.

Sqldependency

This attribute identifies the string value of a group of database/table name pairs. The output cache of pages or controls depends on these name pairs. Note: The sqlcachedependency class monitors the tables in the database on which the output cache depends. Therefore, when items in the table are updated, table-based round robin is used to remove these items from the cache. When the notification (in SQL Server 2005) is used with the commandnotification value, the sqldependency class is used to register the query notification with the SQL Server 2005 server. In addition, the commandnotification value of the sqldependency attribute is only valid on the ASP. NET page. The control can only use table-based round robin For the @ outputcache command.

Varybycontrol

This attribute uses a semicolon-separated string list to change the output cache of the user control. These strings represent the ID attribute values of the ASP. NET Server Control declared in the user control. This attribute is required in the @ outputcache command unless the varybyparam attribute is already included.

Varybycustom

It is used to customize any text required by the output cache. If the property value is browser, the cache varies with the browser name and major version information. If you enter a custom string, you must re-write httpapplication. getvarybycustomstring in the global. asax file of the application.

Varybyheader

This attribute contains the HTTP header list separated by semicolons to change the output cache. When this attribute is set to multiple headers, the output cache contains different versions of a request document for each specified header. The varybyheader attribute enables cache items in all HTTP 1.1 caches, not limited to ASP. NET caches. The @ outputcache command in the user control does not support this attribute.

Varybyparam

This attribute defines a semicolon-separated string list to change the output cache. By default, these strings correspond to the query string values sent using the get method attribute, or to parameters sent using the POST method. When this attribute is set to multiple parameters, the output cache contains different versions of the Request Document for each specified parameter. Possible values include "NONE", "*", and any valid query string or post parameter names. It is worth noting that this attribute is required when the ASP. NET page is cached. It is also required for user controls, unless the varybycontrol attribute is included in the @ outputcache command of the user control. If not, a analyzer error occurs. If you do not need to change the cache content with any specified parameter, you can set this value to "NONE ". If you want the output cache to change according to all parameter values, set the attribute to "*".

Create page output cache file dependency

Sample Code: Response. addfiledependency (mappath ("test. xml "));
To establish a Multi-file dependency, use the addfiledependencies () method.

Set page cache expiration by programming

Sample Code: httpresponse. removeoutputcacheitem (page. resolveurl ("~ /Test. aspx "));
This method only accepts one "virtual absolute" path, so the page. resolveurl () method is required for conversion.

Use programming to set expiration time for multiple page caches (key dependency ))

Sample Code:
Cache page: pageload:
Cache. insert ("key", datetime. Now );
Response. addcacheitemdependency ("key ");
Add dependencies to multiple pages using this method
Remove dependency: pageload:
Cache. Remove ("key ");

Operate the page output cache programmatically

Operation Method of the httpcachepolicy class object exposed by the response. cache attribute.

Create page output cache Configuration

<System. Web>
<Caching>
<Outputcachesettings>
<Outputcacheprofiles>
<Add name = "cacheprofile1" Duration = "60"/>
</Outputcacheprofiles>
</Outputcachesettings>
</Caching>
</System. Web>

2. Partial page Cache

Cache replacement

Use the declaration method. Use the substitution control to set the method required for the methodname attribute. This method must be a static method because the page instance has not been created when the current page outputs the cache. Note: The adrotator uses the cache instead.

Use response. writesubstitution () method. Advantages: 1. The method referenced by this method is not necessarily the method of the current class, but can be the strength or static method of another class. 2. You can use this method in the custom control to implement cache and then replace it.

Partial page cache: User Control Cache

Add the <% @ outputcache %> command to the user control. This command contains a shared property that can be setShared user control output Cache.

Set the user control cache programmatically

When the user control contains the <% @ outputcache %> command, you can control how to modify the cache space by controlling the attributes of the instance of the controlcachepolicy class exposed by the cachepolicy attribute of the user control.

Create File dependencies cached by user controls

You can use the cachecontrolpolicy. Dependency attribute to create a dependency between a cached user control and a file in the file system. Example code:
Pageload:
Cachedependency depend = new cachedependency (mappath ("~ /Test. xml "));
This. cachepolicy. Dependency = depend;

User Control for caching dynamic loading

You can use the page. loadcontrol () method to load the user control. When the user control with the cache feature is loaded, Asp.net framework automatically wraps the user control by using an instance of the partialcachingcontrol class. Sample Code:
Pageload:
Partialcachingcontrol cacheme = (partialcachingcontrol) page. loadcontrol ("test. ascx ");
Cacheme. cachepolicy. setexpires (datetime. Now. addseconds (10 ));
Placeholder1.controls. Add (cacheme );
Lable1.text = cacheme. cachepolicy. Duration. tostring ();

3. Use datasource Cache

The sqldatasource, objectdatasource, and xmldatasource controls all include the attributes used to cache datasource bearer. The advantage is that the data source control can automatically reload data when data is updated. In addition, the same data can be shared among multiple pages and identified by combining attributes: selectcommand, selectparameters, and connectionstring. If the attributes are the same, the same cached data is shared.

Set cache expiration policies by setting properties

Including absolute cache (enablecaching = "true" cacheduration = "XXX") and sliding cache (enablecaching = "true" cacheexpirationpolicy = "sliding" cacheduration = "XXX ")

Cache using objectdatasource Control

You can set the enablecaching, cacheexpirationpolicy, cacheduration attributes of the control, and the method name specified by selectmethod.

Use xmldatasource control to cache

Set the datafile attribute to create a file dependency.

Create a data source control key-value dependency

Procedure
1. Set the cachekeydependency attribute (key) of the data source control );
2. Create an initialized (key) cache project in global. asax. The Code is as follows:
Void application_start (Object sender, eventargs E)
{
Httpcontext context = httpcontext. Current;
Context. cache. insert (
"Key", datetime. Now, null, datetime. maxvalue, cache. noslidingexpiration, cacheitempriority. notremovable, null
);
}
3. Remove the cache item (key) from the page for changing data );
For example, if a cache item is re-inserted in the iteminserted event of the detailsview control, each datasource dependent on this key will automatically reload the data. The Code is as follows:
Protected void detailsview_iteminserted (Object sender, detailsviewinsertedeventargs E)
{
Cache. insert ("key", datetime. Now );
}
Note: The preceding key value is not required at the current time.

4. cache object

You can add almost any objects to the cache. For example, you can add custom controls, dataset, datatable, arraylist, and list to the cache. Note: to use any items returned from the cache, you should always check whether the project is empty. If a project has been deleted, when you attempt to read from the cache in the future, the return value is null.
View msdncache members for details
Sample Code for adding a data cache to a cache object:
Void page_load ()
{
Datatable dt = (datatable) cache ["dtkey"];
If (Dt = NULL)
{
Dt = getdtfromdb (); // The call method here returns the data item datatable from the database
Cache. insert ("dtkey", DT, null, datetime. Now. addhours (1), cache. noslidingexpiration); // Add a project using the absolute expiration policy.
}
Gridview1.datasource = DT;
Gridview1.databind ();
}
Private datatable getdtfromdb ()
{
// Omitted ......
}

Add a project with dependency

Asp.net framework includes three cache Dependencies
1. cachedependency -- used to create a file dependency or cache key-value dependency.
2. sqlcachedependency -- used to create a dependency on Microsoft SQL Server database tables or SQL Server 2005 database queries.
3. aggregatecachedependency -- used to create dependencies using multiple cachedependency objects. For example, you can use this object to combine files and SQL dependencies.

The cachedependency class is the base class, and the other two classes are inherited from the class.

Cache Project Priority

You can specify any value of cacheitempriority Enumeration type.

Configure Cache

View the msdn caching element for details

5. Use SQL cache Dependencies

Asp.net framework supports two types of SQL cache dependencies: pull and push. The first mode is implemented using ASP. NET for table round-robin, and the second mode uses the query notification function of SQL Server 2005. You can use pull SQL cache dependencies for any recent version of ms SQL Server, including ms SQL Server 2005 Express, ms SQL Server 2000, and ms SQL Server 7.0. The second type of push cache dependency can only be used for ms SQL Server 2005 and ms SQL Server 2005 Express, because they depend on the Service Broker of SQL Server.

Use to pull SQL cache Dependencies

In essence, pulling SQL cache depends on using the database Tigger. When the table is modified, Tigger is triggered, and a row of data in the data table named aspnet_sqlcachetablesforchangenotification is updated to record the modification, asp.net framework uses a background thread to regularly pull data table modification information. If any modification is made, the cache project dependent on the data table is removed.
Configure the dependency for pulling SQL cache:
1. SQL cache dependency must be enabled for one or more database tables.

You can use the sqlcachedependencyadmin class in the framework to configure the SQL database to support pulling SQL cache dependencies. To call the methods of this class, you need to create tables, stored procedures, and triggers. For security considerations, the Asp.net process should not be granted these permissions, but be used using a command line tool.
For details about aspnet_regsql, visit the msdn ASP. net SQL Server registration tool (aspnet_regsql.exe)

Brief steps: 1. Enable the SQL cache dependency of a specific database.
Aspnet_regsql-c "Data Source = localhost; Integrated Security = true; initial catalog = pubs"-ed
2. Enable the SQL cache dependency for a specific table.
Aspnet_regsql-c "Data Source = localhost; Integrated Security = true; initial catalog = pubs"-ed-T titles

2. You must configure the SQL cache dependency in the Web configuration file.
<! -- Caching section group -->
<Caching>
<Sqlcachedependency enabled = "true" polltime = "1000"> // set polltime to regularly pull database modifications
<Databases>
<Add name = "northwind"
Connectionstringname = "northwindconnectionstring1"
Polltime = "1000"
/>
</Databases>
</Sqlcachedependency>
</Caching>

A. Dependency on pulling SQL cache for page output Cache: <% @ Outputcache %> specify the sqldependency attribute value: Database Name and table name (mydatabase: mytable );

B. Dependency on using the datasource control to pull SQL Cache: Specify the Database Name and table name (mydatabase: mytable) for the sqldependency attribute of the datasource control );

C. Dependency on Using Cache objects to pull SQL Cache:

Void page_load ()
{
Datatable dt = (datatable) cache ["dtkey"];
If (Dt = NULL)
{
Dt = getdtfromdb (); // The call method here returns the data item datatable from the database
Sqlcachedependency sqldepend = new sqlcachedependecy ("mydatabase", "mytable ");
Cache. insert ("dtkey", DT, sqldepend );
}
Gridview1.datasource = DT;
Gridview1.databind ();
}
Private datatable getdtfromdb ()
{
// Omitted ......
}

Use push SQL cache dependency

The service broker can automatically send a message to the application when the data in the database changes.
Benefit: The Asp.net application does not need to regularly pull database modifications.
Disadvantage: There are many restrictions on the query type (for example, if two parts are required, the query type is abo. mytabel: the query must contain a column name that indicates that * cannot be used, views and temporary tables cannot be referenced, and subqueries, external connections, and subconnections cannot be included, large objects cannot be referenced, distinct, compute, compute by, insert keywords cannot be used, and many Aggregate functions cannot be included)

1. Configure the database for the push SQL cache dependency
Enable ms SQL Server 2005 Service Broker:
A. You can query whether to activate a specific database by using select name, is_broker_enabled from sys_databases.
B. Enable it by using alter database mybase set enable_broker.
C. grant the required permissions to the local ASPNET account, for example, grant subscribe query privileges to "yourserver \ ASPnet"

2. configure applications for pushing SQL cache Dependencies
Void application_start (Object sender, eventargs E)
{
String constring = webconfigurationmanager. connectionstrings ["mycontention1"]. connectionstring;
Sqldependency. Start (constring );
Httpcontext context = httpcontext. Current;
Context. cache. insert (
"Key", datetime. Now, null, datetime. maxvalue, cache. noslidingexpiration, cacheitempriority. notremovable, null
);
}

A. Use the push SQL cache dependency for the page output Cache:
When caching the entire Asp.net page, you can use the push SQL cache dependency. If the results of any SQL commands on the page change, the page will automatically expire from the cache.
The sqlcommand object contains the icationicationautoenlist attribute, which defaults to true. When icationicationautoenlist is enabled, a push cache dependency is automatically created between the page and command. Note that the selectcommand of sqldatasource must meet the query requirements.

B. dependency on the datasource control using the push SQL Cache:
You only need to set the sqlcachedependency attribute. Set sqlcachedependency = "commandnotification"

C. Use the SQL push cache dependency for cache objects:
Void page_load ()
{
Datatable dt = (datatable) cache ["dtkey"];
If (Dt = NULL)
{
String constring = webconfigurationmanager. connectionstrings ["mycontention1"]. connectionstring;
Sqldatadapter dad = new sqldataadapter ("select a, B from DBO. mytable", constring); // note that the query meets the requirements
Sqlcachedependency sqldepend = new sqlcachedependecy (DAD. selectcommand );
Dt = new datatable ();
Dad. Fill (DT );
Cache. insert ("dtkey", DT, sqldepend );
}
Gridview1.datasource = DT;
Gridview1.databind ();
}
Note that the example of the sqlcachedependency class is created. A sqlcommand object is passed to the constructor of the sqlcachedependency class. If the sqlcommand result changes, the datatable will automatically expire from the cache. The order of these commands is very important. The sqlcachedependency object must be created before the command is executed. If the fill () method is called before the sqlcachedependency object is created, the dependency is ignored.

So far, the cache summary has ended. This chapter only contains some key points of knowledge, and the specific application should be case-based.

Transferred from: http://www.cnblogs.com/wenanry/archive/2008/08/13/1267028.html
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.