ASP. NET Cache Technology

Source: Internet
Author: User

When cache is used, it is actually changed from response-> execution-> explicit delivery to response-> explicit delivery. The "execution" in the middle is saved and the efficiency is improved. There are generally four types of cache technology.
I. Output Caching
Due to some features of IIS, the Output Cache is enabled by default. However, to Cache some requests, developers must also customize the Output Cache. By default, the Output Cache is cached on the hard disk. You can modify the DiskCacheable attribute to determine whether to Cache the Output Cache. You can also configure the Cache file size in Web config.

<% @ OutputCache Duration = "3600" VaryByParam = "state" DiskCacheable = "true" %>
Hard disk cache is generally used because the page display data is relatively large. Compared with the memory cache, it has a large capacity, but the access speed is slow. If the cycle is set too short, hard disk cache is inefficient. There are two ways to customize the Output Cache: one is based on the underlying API technology and the other is based on the high-level @ OutputCaching:

1. Based on high-level @ OutputCaching

A. changes the cache content by parameters: Sometimes we need to generate pages based on user requests, but there are only a limited number of combinations of user requests, in this case, several cache pages can be generated based on user requests for caching.

<% @ OutputCache Duration = "60" VaryByParam = "state" %> <asp: SqlDataSource ID = "sqlperformance1" runat = "server">
<SelectParameters>
<Asp: QueryStringParameter Name = "state" QueryStringField = "state" DefaultValue = "CA"/>
</SelectParameters>
</Asp: SqlDataSource>
B. Callback cache: you can insert dynamic parts into the page for each request to make up for the insufficiency of using static cache separately:
The dynamic part uses the Substitution control, which is a container.

<Asp: Substitution ID = "Substitution1" runat = "server" MethodName = ""/>
Put the content of the method to be called in MethodName.
2. Use APIs to customize cache:
Configure System. Web. HttpCachePolicy

<% @ OutputCache Duration = "60" VaryByParam = "none" %>
You can write it

Response. Cache. SetExpires (DateTime. Now. AddSeconds (60 ));
Response. Cache. SetCacheability (HttpCacheability. Public );

Ii. Fragment Caching
As an additional function of the Output cache, OSS also provides a caching technology for caching user controls. Set in the user control:

 

<% @ OutputCache Duration = "60" VaryByParam = "none" %>
However, the cache is not set on the page that references the user control. In this case, all the user controls on the page are static and dynamic.
The cache user space can also use controls as the parameter source. By specifying the control as the data source of the cache control, you can cache the control data.

Iii. Data Caching
Asp.net provides a very quick way to cache databases. Users can cache page variables easily and easily. To improve program efficiency. The cache lifecycle of a page variable is the same as that of an application.
The implementation is to put the data in the Cache, such:

Source = new DataView (ds );
Cache ("MyCache") = source;
The variable MyCache is actually an XML file.

Iv. SQL Caching
By configuring the database connection pool, the cache changes only when the database data is changed.
Open a DOS window:
C: \> dir aspnet_regsql.exe/s -- this file is specially registered for the SQL connection pool. It has special support for SQL Sever 7.0 and later versions, by writing some special statements to configure this registration connection pool, we can connect the connection pool to a local application (Asp.net server, or IIS. The connection pool can only monitor a limited number of databases, otherwise the load of the connection pool is too large. Use SQL Caching:
First register, such as: aspnet_regsql.exe-S ". \ SQLExpress"-E-d "pubs"-ed
Aspnet_regsql.exe-S & quot;. \ SQLExpress & quot;-E-d & quot; pubs & quot;-et-t & quot; authors & quot"
-S ". \ SQLExpress" indicates that the SQL Server instance to be used is ". \ SQLExpress ". -E indicates that the current windows credential is used for authentication. -D "pubs" indicates that the database name used for application services is "pubs ". -Ed indicates that the database is enabled for the SQL cache dependency. -Et indicates that the table is enabled for the SQL cache dependency. -T "authors" table name is "authors ".
Then on the page:
<% @ OutputCache Duration = "99999999" VaryByParam = "none" SqlDependency = "Pubs. Authors" %> is OK.

========================================================== ==================================
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 your product directory allows users to view the directory Page Based on categoryID and page variables, you can use 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.

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, after slight processing, you can also include changes to specific tables in the database.

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 ).

 

This article is from "new-fighter"
 

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.