Make full use of ASP. NET three caches to improve site performance (1)

Source: Internet
Author: User

ASP. NET provides three main forms of cache: page-level output cache, userWidgetLevel output cache or segment cache) and cache API. The advantage of output cache and fragment cache is that it is very easy to implement. In most cases, it is sufficient to use these two caches. The cache API provides additional flexibility, which is actually quite flexible) and can be used to exploit the cache at each layer of the application. This article comprehensively introduces the application of these three caching technologies in all layers of the system.

Among the many features provided by ASP. NET, cache support is undoubtedly my favorite feature. I have a good reason to say so. Compared with all other ASP. NET features, caching has the greatest potential impact on the performance of applications. With caching and other mechanisms, ASP. NET developers can accept high overheadWidgetFor example, DataGrid) additional overhead during site construction, without worrying about the performance being greatly affected. To maximize the use of caching in applications, you should consider implementing caching at all program levels.

Steve's cache prompt

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.

Cache can prevent 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 try to optimize code orDatabaseYou can obtain the required performance. You will definitely select the cache solution, assuming that 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 in the future.

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

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 specifies the Location where the output should be cached. To specify this parameter, it must be Any, Client, Downstream, None, Server, or ServerAndClient.

Required attribute of VaryByParam. 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 allows you to specify custom changes in global. asax, for example, "Browser ").

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 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, it is acceptable for one hour. Therefore, 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 beBrowserAs the mobile phone client presents the output, different content versions must be cached for different clients. Alternatively, the page may have been optimized for IE. For Netscape or Opera, the optimization function should be canceled. The next example is very common. We will provide an example to illustrate how to achieve this goal:

Example: VaryByCustom is supportedBrowserCustom

To enableBrowserEach has a separate cache entry. The value of VaryByCustom can be set to "browser ". This function has been built in the cache module and will be applicable to eachBrowserName and major version insert a separate page Cache version.

<% @ OutputCache Duration = "60" VaryByParam = "None" VaryByCustom = "browser" %>

Fragment cache, userWidgetOutput 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 fragment caching and users.WidgetCache. In addition, menus and other layout elements, especially those dynamically generated from the data source, can also be cached in this way.

If needed, you can selectWidget:

1)WidgetThe property of has changed

2) any page orWidgetStatus Change

OnceWidgetAfter caching, you can share these with hundreds of pages.WidgetInstead of retaining a separateWidgetCache version.

Implementation

The syntax used by the fragment cache is the same as that used by the page-level output cache, but it is applied to users.Widget. Ascx file) instead of the Web form. aspx file ). Except for the Location attribute, for all attributes supported by OutputCache on Web formsWidgetAlso supported. UserWidgetThe OutputCache attribute named VaryByControl is also supported.WidgetUsually on the pageWidgetFor example, DropDownList ).Widget. If VaryByControl is specified, You can omit VaryByParam. Finally, by defaultWidgetCache them separately. However, if a userWidgetIt does not change with the page in the application, and the same name is used on all pages, you can set the value of the Shared parameter to "true", this parameter will make the userWidgetFor reference.Widget.

Example

<% @ OutputCache Duration = "60" VaryByParam = "*" %>

This example caches the userWidget60 seconds.WidgetCreate separate cache entries for each page.

<% @ OutputCache Duration = "60" VaryByParam = "none"
VaryByControl = "CategoryDropDownList" %>

This example caches the userWidget60 seconds, and will be targeted at CategoryDrop

DownListWidgetFor thisWidgetCreate separate cache entries for each page.

<% @ OutputCache Duration = "60" VaryByParam = "none" VaryByCustom = "browser"
Shared = "true" %>

Finally, this example caches the userWidget60 seconds, andBrowserName and major version to create a cache entry. Then, eachBrowserWill be referenced by this userWidgetAs long as all pages reference thisWidget).

Cache API, Using Cache objects

Page-level and userWidgetThe level output Cache is indeed a method that can quickly and easily improve the performance of the site. However, 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 an object was cached, the time since the object was last accessed, changes to files or folders, and changes to other cached objects, after slight processing, you can also includeDatabaseChanges to a specific table.

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 the cached object, while Insert () does not return a value that is 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 the key "key" does not exist in the cache, or if the object associated with the key expires or is updated, the "dependentkey" cache entry 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: you cannot use it together if you absolutely expire or if you scroll to expire.

Cache. Insert ("key", myFrequentlyAccessedData, null,
System. Web. Caching. Cache. NoAbsoluteExpiration,
TimeSpan. FromMinutes (1 ));

Dynamic rolling 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: Dynamic rolling expiration and absolute expiration cannot be used together.


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.