ASP. Net cache summary and analysis

Source: Internet
Author: User

1. Page Cache

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

<% @ OutputCache CacheProfile = "" 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

Copy codeThe Code is as follows: <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 allows you to set the output cache of the Shared user control.

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:

Copy codeThe 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:Copy codeThe 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:

Copy codeThe Code is as follows: 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.

Copy codeThe Code is as follows: <! -- 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. Pull SQL cache dependency for the page output cache: <% @ OutputCache %> specify the sqlDependency attribute value: Database Name and table name (Mydatabase: Mytable );

B. Pull SQL cache dependency on the DataSource control: Specify the Database Name and table name (Mydatabase: Mytable) for the sqlDependency attribute of the DataSource control );

C. Dependency on pulling SQL Cache objects:

Copy codeThe Code is as follows: 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"

That is to say, SQL cache currently only supports ms SQL server 2005 or later, and they only have dependency notifications. Otherwise, the cache is invalid.

2. configure applications for pushing SQL cache Dependencies

Copy codeThe Code is as follows: 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:Copy codeThe Code is as follows: 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.

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.