Cache Technology Basics

Source: Internet
Author: User

Basic Cache Technology favorites

1. Introduction
A large number of website pages are dynamically created based on different requests submitted by users. As we know, dynamic pages help provide customized dynamic content according to user requirements. Dynamic pages are also used to obtain information updated every moment in the database. The disadvantage is that the system overhead is added for generating the same page for each user request.
ASP. NET provides the caching technology to help us solve this problem to the greatest extent possible. It can cache the output page, save it in the memory, and cache the content requested by the user. The cache features can be customized according to different methods.
This article mainly introduces the cache technology of ASP. NET. This section describes the usage and Client Cache problems.
2. ASP. NET Cache
Caching is a programming technology that stores data that requires frequent and fast access in applications in the memory. ASP. NET provides three main forms of cache: page-level output cache, user control-level 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 (actually quite flexible) and can be used to take advantage of the cache at each layer of the application. This article only describes page-level cache and user control-level cache.
2.1. page caching
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 ).
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.
& #61548; duration: Required attribute. The time when the page should be cached, in seconds. Must be a positive integer.
& #61548; Location: Specifies the location where the output should be cached. To specify this parameter, it must be any, client, downstream, none, server, or serverandclient.
& #61548; 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.
& #61548; varybyheader: Changes cache entries based on changes in the specified header.
& #61548; varybycustom: allows 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 ).
2.2. Fragment caching
ASP. NET provides some caching or regional caching functions for web forms. This technology can be used when you want to implement more control over the cache on a specific page.
To specify the user control to be cached, we use the @ outputcache command, just like the usage of the entire page cache.
<% @ Outputcache duration = 10 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.
You can also set the property shared = "true" to allow all pages using it to share the control cache.
3. Conclusion and Suggestion
Cache should be implemented 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 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.
ASP.. Net cache and IE cache are not the same concept. ie cache may cause errors and is difficult to control. You can consider disabling ie cache, but only using ASP.. Net cache mechanism.
For the particularity of our web system, there are a large number of pages for different users to display different data, so when using the ASP. NET cache mechanism, please be very careful. You can consider adding some necessary parameters when using the cache mechanism.

 

 

[Introduction]

ASP. NET provides three main forms of cache: page-level output cache, user control-level output cache (or segment cache), and cache API. The advantage of slow output memory 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 (in fact, considerable flexibility) and can be used to exploit the cache at each layer of the application program. 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 ASP. all other features of. net, the cache has the greatest potential impact on the application performance, using the cache and other mechanisms, Asp. NET developers can accept the additional overhead when building a site using a control with a large overhead (for example, DataGrid), without worrying that the performance will be 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 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 by Using 80%. Therefore, to improve performance, you should first think of slow storage. 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, 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.

<% @ Outputcacheduration = "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 (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 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 present the output to both the browser and mobile phone client. Because of this, 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 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.

<% @ Outputcacheduration = "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. In addition, menus and other layout elements, especially those dynamically generated from the data source, can also be cached in this way.

If necessary, you can select the control to be cached based on the following conditions:

(1) The property of a control has changed

(2) changes in the status of any page or control supported by the page-level output Cache

Once some controls are cached, they can be shared with hundreds of pages without the need to retain separate control cache versions 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. This attribute changes the control's cache based on the value of a member of the user control (usually a control on a page, for example, dropdownlist. 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 set the value of the shared parameter to "true ", this parameter allows the cached version of the control to be used on all pages that reference the control.

Example

<% @ Outputcacheduration = "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.

<% @ Outputcacheduration = "60" varybyparam = "NONE"
Varybycontrol = "categorydropdownlist" %>

This example caches the user control for 60 seconds and

Each different value of the downlist control creates a separate cache entry for each page where the control is located.

<% @ Outputcacheduration = "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 ).

Cache API, Using Cache objects

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. Using Cache objects, you can store any serializable Data Objects and control the expiration of cache entries based on a 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 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 the cache does not contain a key named "key", or if the object associated with the key expires or is updated, the "dependentkey" slow-down entry will expire.

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 either the expiration date or the rolling expiration date (see below.

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.

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 the cached object 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. cacheitemremovedcallbackcallback = 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 any logic defined in the appendlog () method to record the reason why the cached data expires. 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 cacheditemexpiredbut.

Notremovedcallback. If this callback is defined, the execution must be completed before the cache item is deleted.

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 (boolbypasscache)
{
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:

1) Some values (such as cachekey, cacheitem, and cache duration) are defined at one time and only once.

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

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

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

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

Sample Code related to this article (cacheddemo. msi, see the example CD in this book) is a helper class that will handle all the above situations and can write only one or two lines of code to access the cached data.

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.

 

 

ASP. NET cache: a collection of method analysis and practice examples

Cache as early as possible; cache should be implemented at every 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 errors. caching is a way to achieve "good enough" performance without having to spend a lot of 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. The page-level output cache is the simplest form of cache. The output cache only keeps 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 ). 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 is required. 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. Varybyparam is required. 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 (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 so that each browser has 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" %>

Fragment Caching: the user control outputs the cache and caches the entire page. This 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. The syntax used to implement segment caching is the same as that used for 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, A separate cache entry will be created for each change in 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 after 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.

 

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.