Asp tutorial. net various page cache details
Implementation
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
Specify the location where the output should be cached. To specify this parameter, it must be Any, Client, Downstream, None, Server, or ServerAndClient.
VaryByParam
Required attribute. 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
Allow 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 the product directory allows you 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 and provides an example to illustrate how to achieve this goal:
Example: VaryByCustom is used to support browser customization.
To make each browser have 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" %>
Segment cache, user control output cache
Caching the entire page 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.
Implementation
The syntax used by fragment caching is the same as that used by 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 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" %>
This example caches the user control for 60 seconds, and creates separate cache entries 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 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 in ASP. NET, the real flexibility and powerful functions of the 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, changes to specific tables in the database tutorial can also be included after slight processing.
Store data in Cache
The simplest way to store data in a Cache is to assign values to a key, just like a HashTable or Dictionary object:
Cache ["key"] = "value ";
This method stores items in the cache without any dependencies, so it does not expire unless the cache engine deletes the items to provide space for other cached data. To include specific cache dependencies, you can use the Add () or Insert () methods. Each method has several reloads. The only difference between Add () and Insert () is that Add () returns a reference to a cached object, while Insert () does not return a value (null in C, in VB ).
Example
Cache. Insert ("key", myXMLFileData, new System. Web. Caching. CacheDependency (Server. MapPath ("users. xml ")));
In this example, the xml data in the file can be inserted into the cache, without reading from the file in future requests. CacheDependency is used to ensure that the cache expires immediately after the file is changed, so that the latest data can be extracted from the file and cached again. If the cached data comes from several files, you can also specify an array of file names.
Cache. Insert ("dependentkey", myDependentData, new System. Web. Caching. CacheDependency (new string [] {}, new string []
{"Key "}));
In this example, the second data block with the key value "key" can be inserted (depending on whether the first data block exists ). If a key named "key" does not exist in the cache, or if the item associated with the key expires or is updated, the cache entry of "dependentkey" expires.
Cache. Insert ("key", myTimeSensitiveData, null, DateTime. Now. AddMinutes (1), TimeSpan. Zero );
Absolute expiration: In this example, the cache will be cached for one minute, and the cache will expire after one minute. Note: the absolute expiration and sliding expiration (see below) cannot be used together.
Cache. Insert ("key", myFrequentlyAccessedData, null,
System. Web. Caching. Cache. NoAbsoluteExpiration,
TimeSpan. FromMinutes (1 ));
Sliding expiration: this example caches frequently used data. The data will be kept in the cache until it has not been referenced for up to one minute. Note: Slide expiration and absolute expiration cannot be used together.
More options
In addition to the dependencies mentioned above, we can also specify the priority of items (low, high, NotRemovable in sequence, they are in the System. web. caching. cacheItemPriority) and the CacheItemRemovedCallback function called when an item in the cache expires. Most of the time, the default priority is enough-the cache engine can normally complete tasks and handle cache memory management. The CacheItemRemovedCallback option takes into account some interesting possibilities, but in fact it is rarely used. However, to illustrate this method, I will provide an example of its usage:
CacheItemRemovedCallback example
System. Web. Caching. CacheItemRemovedCallback callback = new System. Web. Caching. CacheItemRemovedCallback (OnRemove );
Cache. Insert ("key", myFile, null,
System. Web. Caching. Cache. NoAbsoluteExpiration,
TimeSpan. Zero,
System. Web. Caching. CacheItemPriority. Default, callback );
...
Public static void OnRemove (string key,
Object cacheItem,
System. Web. Caching. CacheItemRemovedReason reason)
{
AppendLog ("The cached value with key" + key +
"Was removed from the cache. Reason:" +
Reason. ToString ());
}
This example uses the AppendLog () method (this method is not discussed here, see any logic defined in Writing Entries to Event Logs) to record the reason for cache data expiration. When deleting items from the cache and recording the reason for deletion, you can determine whether the cache is effectively used or whether you may need to increase the memory on the server. Note: callback is a static (Shared in VB) method. We recommend that you use this method because if you do not use it, the instance of the class that saves the callback function will be kept in the memory, to support callback (not required for static/Shared methods ).
This feature has a potential use-refresh cached data in the background so that you never have to wait for data to be filled, but the data remains relatively new. But in fact, this feature is not applicable to the current version of the cache API, because the callback is not triggered or not completed before the cached items are deleted from the cache. Therefore, the user will frequently send a request to access the cache value, and then find that the cache value is empty and has to wait for the cache value to be refilled. I want to see an additional callback in future ASP. NET versions, which can be called CachedItemExpiredButNotRemovedCallback. If this callback is defined, it must be completed before deleting the cache item.
Cache data reference mode
Whenever we try to access the data in the cache, we should consider a situation where the data may no longer be in the cache. Therefore, the following pattern should be applicable to your access to the cached data. In this case, we assume that the cached data is a data table.
Public DataTable GetCustomers (bool BypassCache)
{
String cacheKey = "CustomersDataTable ";
Object cacheItem = Cache [cacheKey] as DataTable;
If (BypassCache) (cacheItem = null ))
{
CacheItem = GetCustomersFromDataSource ();
Cache. Insert (cacheKey, cacheItem, null,
DateTime. Now. AddSeconds (GetCacheSecondsFromConfig (cacheKey ),
TimeSpan. Zero );
}
Return (DataTable) cacheItem ;}
Note the following points about this mode:
Some values (such as cacheKey, cacheItem, and cache duration) are defined at one time and only once.
You can skip the cache as needed-for example, when a new customer is registered and redirected to the customer list, the best way is to skip the cache and refill the cache with the latest data, this data includes newly inserted customers.
The cache can only be accessed once. This method improves performance and ensures that NullReferenceExceptions does not occur because the item exists during the first check, but has expired before the second check.
This mode uses the strong type check. The "as" operator in C # tries to convert the object to the type. If the object fails or is empty, only null (null) is returned ).
The duration is stored in the configuration file. Ideally, all cache dependencies (whether File-based, time-based, or other types of dependencies) should be stored in the configuration file, this allows you to make changes and easily measure performance. We also recommend that you specify the default cache duration. If you do not specify the duration for the used cacheKey, use the default duration for the GetCacheSecondsFromConfig () method.
An example of the relevant code is a helper class, which will handle all the above cases, but allows one or two lines of code to access the cached data. Download CacheDemos. msi.
Summary
Caching can greatly improve the performance of applications. Therefore, you should consider designing applications and testing the performance of applications. Applications always benefit from caching more or less. Of course, some applications are more suitable for caching than other applications. A deep understanding of the cache options provided by ASP. NET is an important skill that any ASP. NET Developer should master.
Early cache; frequent cache
You should implement caching at each layer of the application. 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 mistakes
Caching is a way to achieve "good enough" performance without much time and analysis. The memory is very cheap now, so if you can cache the output for 30 seconds, instead of spending a whole day or even a week trying to optimize the code or database to get the required performance, you will definitely choose a 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.
Page-level output cache
As the simplest form of caching, 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 ).
There are two types of cache:
· Output cache Output caching
· Data caching
1. Output Caching)
With the output cache, you can cache the final output HTML page. When the same page is requested again, ASP. NET does not execute the Page lifecycle and related code, but directly uses the cached page. The syntax is as follows:
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
<% @ OutputCache Duration = "60" VaryByParam = "None" %>
The Duration property setting page will be cached for 60 seconds. Any user request will be cached, and the same request will directly use the cached page within 60 seconds of the buffer. After the cache expires, ASP. NET executes the page code again and creates a new HTML cache for the next 60 seconds.
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
<% @ Page Language = "C #" MasterPageFile = "~ /MasterPage. master "AutoEventWireup =" true"
CodeFile = "OutputCachingTest. aspx. cs" Inherits = "OutputCachingTest" Title = "Untitled Page" %>
<% @ OutputCache Duration = "20" VaryByParam = "None" %>
<Asp: Content ID = "Content1" ContentPlaceHolderID = "ContentPlaceHolder1" runat = "Server">
<Div class = "title"> Output Cache </div>
Date: <asp: Label ID = "lblDate" runat = "server" Text = ""/>
Time: <asp: Label ID = "lblTime" runat = "server" Text = ""/>
</Asp: Content>
Protected void Page_Load (object sender, EventArgs e)
{
LblDate. Text = DateTime. Now. Tow.datestring ();
LblTime. Text = DateTime. Now. ToLongTimeString ();
}
In this example, the page will be cached for 20 seconds.
· Cache by Query String)
In actual application, the page content is changed dynamically based on some parameters. If your page obtains information by querying strings, you can easily cache different copies of the page by querying strings. VarByParam = "None" indicates that ASP. NET only stores one copy of the cached page. VarByParam = "*" specifies that ASP. NET stores different cache pages based on different query strings.
In the preceding example, different ID. ASP. NET in the query string stores a separate cache page for each ID. This method has some problems when querying strings in a wide range. In this case, you can specify the name of an important query string variable in the VarByParam attribute, as shown below:
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
<% @ OutputCache Duration = "60" VaryByParam = "*" %>
<Div align = "right">
<A href = "OutputCachingTest2.aspx"> No Query String </a> |
<A href = "OutputCachingTest2.aspx? Id = 1 "> ID 1 </a> |
<A href = "OutputCachingTest2.aspx? Id = 2 "> ID 2 </a> |
<A href = "OutputCachingTest2.aspx? Id = 3 "> ID 3 </a> |
<A href = "OutputCachingTest2.aspx? Id = 3 & langid = 1 "> ID 3 </a>
</Div>
In this way, ASP. NET can cache different cache versions based on the id or langid.
· Custom cache (Custom Caching)
You can also create a custom program to cache the page. ASP. NET provides a convenient way to create a custom cache. You can use the VarByCustom attribute to specify the name of the custom cache type.
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
% @ OutputCacheDuration = "60" VaryByParam = "id; langid" %
You also need to create a method to generate a custom string for the cache, as follows:
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
Public override stringGetVaryByCustomString (HttpContext context, stringcustom)
{
If (custom = "browser ")
{
Returncontext. Request. Browser. Browser +
Context. Request. Browser. MajorVersion;
}
Else
{
Return base. GetVaryByCustomString (context, custom );
}
}
This method must be written in the global. asax file. ASP.. NET. If this method returns the same string in different requests, ASP. NET will use the cached page, otherwise a new cache version will be generated.
In the preceding example, the GetVaryByCustomString () method creates a cache string based on the browser name. ASP. NET creates caches of different versions based on different browser requests.
Read about wordend:
Use ASP. NET cache to improve site performance
ASP. NET cache: method analysis and practice examples
ASP. NET2.0 revealing reading notes: page output cache
· Control Cache)
The cache technology above allows you to easily cache the entire page. To cache the content of a specified control, you can specify the VaryByControl attribute.
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
% @ OutputCacheDuration = "20" VaryByControl = "MyControl_1" %
The above code ASP. NET will cache the MyControl_1 control for 20 minutes. To cache controls based on some attribute values, you only need to add the OutPutCache command to the *. ascx page.
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
<% @ Control Language = "C #" AutoEventWireup = "true" CodeFile = "MyControl. ascx. cs" Inherits = "Controls_MyControl" %>
% @ OutputCacheDuration = "20" VaryByControl = "EmployeeID" %
......
......
VaryByControl = "EmployeeID" tells ASP. NET to create caches of different versions based on the EmployeeID attribute declared in the control.
Add the EmplyeeID attribute to the. ascx. cs file for ASP. NET cache.
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
Private int_employeeID;
Public intEmployeeID
{
Get {return_employeeID ;}
Set {_ employeeID = value ;}
}
Protected voidPage_Load (objectsender, EventArgs e)
{
LblDate. Text = DateTime. Now. Tow.datestring ();
LblTime. Text = DateTime. Now. ToLongTimeString ();
LblEmployeeID. Text = EmployeeID. ToString ();
}
Add a control on the page and set the employee ID.
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
<% @ RegisterSrc = "Controls/MyControl. ascx" TagName = "MyControl" TagPrefix = "uc1" %>
<Asp: ContentID = "Content1" ContentPlaceHolderID = "ContentPlaceHolder1" runat = "Server">
<Divalign = "center">
<Uc1: MyControlID = "MyControl1" runat = "server" EmployeeID = "1"> </uc1: MyControl>
</Div>
</Asp: Content>
· Cache Profile)
Web. config allows you to configure cache-related settings,
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
<System. web>
<Caching>
<OutputCacheSettings>
<OutputCacheProfiles>
<Addname = "ProductItemCacheProfile" duration = "60"/>
</OutputCacheProfiles>
</OutputCacheSettings>
</Caching>
</System. web>
You can use the preceding configuration by setting the CacheProfile = "ProfileName" attribute:
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
% @ OutputCacheCacheProfile = "ProductItemCacheProfile" VaryByParam = "None" %
2. Data Caching)
ASP. NET also provides another flexible cache type: data cache. You can add time-consuming entries to an object cache set and store them as key values.
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
Cache ["Name"] = data;
You can use the Cache. Insert () method to set Cache expiration, priority, and dependencies.
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
Date1 = DateTime. Now;
Cache. Insert ("Date1", date1, null, DateTime. Now. AddSeconds (20), TimeSpan. Zero );
ASP. NET allows you to set an absolute expiration time or sliding expiration time, but it cannot be used at the same time.
· Cache dependency
Cache dependencies make the cache dependent on other resources. When the dependencies are changed, the cache entries are automatically removed from the cache. Cache dependencies can be files, directories, or keys with other objects in the application's Cache. If the file or directory changes, the cache will expire.
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
Date2 = DateTime. Now;
String [] cacheKeys = {"Date1 "};
CacheDependency cacheDepn = newCacheDependency (null, cacheKeys );
Cache. Insert ("Date2", date2, cacheDepn );
In the preceding example, the "Date2" cache object depends on the "Date1" cache entry. When the "Date1" object expires, "Date2" will automatically expire. The first parameter in CacheDependency (null, cacheKeys) is null because we only monitor changes to the cache key.
· Callback Method and Cache Priority)
ASP. NET allows us to write a callback function that is triggered when cache entries are removed from the cache. You can also set the priority of cache entries.
Code highlighting produced by Actipro zhutiai (freeware)
Http://www.111cn.net/
Protected void Page_Load (object sender, EventArgs e)
{
DateTime? Date1 = (DateTime ?) Cache ["Date1"];
If (! Date1.HasValue) // date1 = null
{
Date1 = DateTime. Now;
Cache. Insert ("Date1", date1, null, DateTime. Now. AddSeconds (20), TimeSpan. Zero,
CacheItemPriority. Default, new CacheItemRemovedCallback (CachedItemRemoveCallBack ));
}
DateTime? Date2 = (DateTime ?) Cache ["Date2"];
If (! Date2.HasValue) // date2 = null
{
Date2 = DateTime. Now;
Cache. Insert ("Date2", date2, null, DateTime. Now. AddSeconds (40), TimeSpan. Zero,
CacheItemPriority. Default, new CacheItemRemovedCallback (CachedItemRemoveCallBack ));
}
// Set values in labels
LblDate. Text = date1.Value. Tow.datestring ();
LblTime. Text = date1.Value. ToLongTimeString ();
LblDate1.Text = date2.Value. Tow.datestring ();
LblTime1.Text = date2.Value. ToLongTimeString ();
}
Private void CachedItemRemoveCallBack (string key, object value, CacheItemRemovedReason reason)
{
If (key = "Date1" | key = "Date2 ")
{
Cache. Remove ("Date1 ");
Cache. Remove ("Date2 ");
}
}
In this example, the "Date1" and "Date2" caches are created. "Date1" expires in 20 seconds and "Date2" is 40 seconds. However, because we have registered the removed callback function, when "Date1" or "Date2" expires, the CachedItemRemoveCallBack method will be executed. In this method, two cache entries are removed, ASP. NET also provides the callback function CacheItemUpdateCallback when processing cache entry updates.