Overview
The academic explanation of caching is "placing common data in a location that is easy to read to improve performance ". For Asp.net, there are a variety of objects to be cached, including the data extracted from the database, static pages generated by the aspx page, and even compiled assembly. The rational use of cache can greatly improve the performance of Asp.net. The following describes the cache mechanism in Asp.net.
Cache category
In Asp.net, most caching mechanisms are stored in cache objects, that is, part of the server memory. When a user requests data, if the data has been cached, the data extracted by the user is directly returned from the server, rather than from the database and other underlying databases. This is helpful for improving performance. The following describes several cache mechanisms in asp.net.
Assembly Cache
To put it simply, this cache is provided by asp.net and requires no developer involvement. That is, when the first request is sent to the server, the Page class and related Assembly are compiled. When the next request is sent, the cached compilation is accessed instead of re-compilation. The CLR will automatically detect code changes. If the code changes, the relevant code will be re-compiled at the next visit.
Data Source Cache
Data Source cache, as its name implies, is the way to use the data source control to cache the obtained data. These controls include SqlDataSource and ObjectDataSource:
As an abstract class, performancecontrol exposes the following attributes for caching:
| Name |
Description |
| CacheDuration |
The data source control caches the data retrieved by the SelectMethod attribute within a period of time. |
| CacheExpirationPolicy |
Gets or sets the cache expiration behavior. This behavior and duration can be combined to describe the cache behavior used by the data source control. |
| CacheKeyDependency |
Gets or sets a user-defined key dependency, which is linked to all data cache objects created by the data source control. |
| EnableCaching |
Gets or sets a value that indicates whether the ObjectDataSource control enables data caching. |
It is very easy to use. You only need to set the cache-related attributes. For example, if you want to cache the current data source for 10 seconds, you only need to set the EnableCaching attribute and the CacheDuration attribute as follows:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" SelectCommand="SELECT top 10 * FROM [Person].[Contact]" EnableCaching="true" CacheDuration="10"></asp:SqlDataSource>
The working principle of this method can be expressed as follows:
For more information about ObjectDataSource, read Caching Data with the ObjectDataSource.
SQL Cache Dependency
You should note that the preceding data source control also exposes the CacheKeyDependency attribute, which is used to implement SQL Cache Dependency. When the content of the database table changes, update the corresponding cache, which is dependent on the underlying database, just as Dependency indicates. The following describes two ways to implement SQL Cache Dependency.
Method 1: Use the polling query mechanism (polling-based ):
This mechanism inserts a special table and five stored procedures starting with AspNet_SqlCacheNotification_Trigger in SQL server. When the data in the monitored table changes, then, a table named AspNet_SqlCacheTablesForChangeNotification is updated, And the Asp.net program checks whether the database content is updated at intervals specified by the user. If the database content is updated, the cached data is updated.
This mechanism is relatively cumbersome. There are many tutorials on the Internet for specific practices. Here I recommend that you read: Using SQL Cache Dependencies.
It is easy to use. You can set it in the OutputCache command in the header of the page and in the external DataSource space. The format is "Database Name: Table name ". the table name is the name of the table to be monitored. The example is as follows:
<%@ OutputCache Duration="30" VaryByParam="none" SqlDependency="DatabaseName:tableName" %>
To add multiple tables, separate them ";"
SqlDependency="database:table;database:table"
Method 2: Use notification-based)
It is much easier to configure the notification mechanism, but the SQL server version must be later than 9.0, that is, SQL server 2005. To use this method, you must enable the SQL server notification service.
You can use the notification mechanism to cache the page or the datasouce control. The cache code for the page is as follows:
<%@ OutputCache Duration="30" VaryByParam="none" SqlDependency="CommandNotification" %>
Note that SqlDependency must be set to CommandNotification.
The datasource control is the same:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" SelectCommand="SELECT top 10 * FROM [Person].[Contact]" EnableCaching="true" CacheDuration="10" SqlCacheDependency="CommandNotification"></asp:SqlDataSource>
Output Cache)
The output cache is a page-level cache that puts the static pages generated after the first request of the aspx page content into the cache. Each request returns a static page from the cache within the non-expiration time, instead of re-completing the lifecycle of Asp.net. You can add the OutputCache command to the page header or use the HttpCachePolicy class.
The output cache can cache the entire page or some pages, and some pages are cached through user controls.
The following describes how to implement page cache using the OutputCache command:
As we have seen above, this method is very simple. Next we will talk about the key attributes of OutputCache.
Duration
Page expiration time, in seconds. After the expiration time is exceeded, the page will be regenerated and cached in the next request.
VaryByHeader
VaryByCustom
VaryByParam
VaryByControl
VaryByContentEncodings
These attributes are used to save multiple versions of the page. For example, if a page is used to display products, different versions of the same page are cached based on the product id. For more information, see MSDN
CacheProfile
This option is similar to a connection string. The function is to convert the specific cache option into a reference to the option. For example, we put the following code in Web. Config:
<caching> <outputCacheSettings> <outputCacheProfiles> <add name="CacheProfile" enabled="true" duration="60" varyByParam="product:id"/> </outputCacheProfiles> </outputCacheSettings> </caching>
You only need to set the following settings in the page header when referencing:
<%@ OutputCache CacheProfile="CacheProfile" %>
Instead of writing all pages
DiskCacheable
Because the server memory is limited, by setting the DiskCacheable attribute to true, you can put the cache page into the hard disk, so that even if the server crashes and restarts, the cache still exists.
Cache Part Page
The implementation principle of a part of the cache page is the same as that of caching the entire page. The OutputCache command is added to the page header. The only difference is that some pages are cached in the user control. I will not talk about this part.
Use HttpCachePolicy to cache pages
As mentioned above, the OutputCache command is used to set the cache option in the page header. Another alternative method is to use the HttpCachePolicy class. The instance of this class is Response. cache. if you use HttpCachePolicy to set the cache, you need to remove the OutputCache command from the page.
For example:
<%@ OutputCache Duration="30" VaryByParam="state;city" %>
It is equivalent to the following code:
Response.Cache.SetExpires(DateTime.Now.AddSeconds(30)); Response.Cache.VaryByParams["state"] = true; Response.Cache.VaryByParams["city"] = true;
For more information about HttpCachePolicy, see MSDN
Object Cache
Object Caching caches objects inherited from System. Object in the server's memory. You can access the Cache set through the Cache attribute of the Page class. Any type of objects can be stored in the Cache, but be careful when using the Cache, because the Cache occupies the server memory. improper use may drag down the performance.
Example of Using Cache:
//save object into Cache Cache["table"] = GridView1; //get object from Cache GridView gv = (GridView)Cache["table"];
Note that when you extract the objects in the cache, do not forget to forcibly convert them.
Summary
This article briefly describes the cache mechanism of Asp.net, And the cache in asp.net greatly simplifies the use of developers. If used properly, the program performance will be objectively improved.