ASP. NET provides three main forms of caching: page-level output caching, user control-level output caching (or fragment caching), and caching APIs.
The benefits of output caching and fragment caching are very easy to implement, and in most cases, using both caches is sufficient. The caching API provides additional flexibility (which is actually quite a lot of flexibility) that can be used to leverage caching at every level of the application.
Steve's Cache hints
Cache early; cache frequently
You should implement caching at every level of your application. Add cache support to the data tier, business logic layer, UI, or output layer. Memory is now very inexpensive-so you can get a lot of performance gains by implementing caching in an intelligent way throughout your application.
Caching can mask many faults
Caching is a way to get "good enough" performance without a lot of time and analysis. Again, memory is now very inexpensive, so if you can get the performance you need by caching the output for 30 seconds instead of trying to optimize the code or database for a full day or even a week, you will definitely choose the caching solution (assuming you can accept 30 seconds of old data). Caching is one of those features that leverages 20% to get 80% return, so to improve performance, you should first think of caching. However, if the design is bad, it may end up with undesirable consequences, so you should, of course, design the application as correctly as possible. But if you just need to get high enough performance right away, the cache is your best option, and you can redesign your application as soon as possible at a later time.
1 page-level output caching
As the simplest form of caching, the output cache is simply a copy of the HTML that is left in memory to be sent in response to the request. Subsequent requests will provide the cached output until the cache expires, so that performance is likely to be greatly improved (depending on how much overhead is required to create the original page output-the output of the send cache is always fast and relatively stable).
Realize
To implement a page output cache, simply add a OutputCache instruction to the page.
<%@ OutputCache duration= "*" varybyparam= "*"%>
As with other page directives, the directive should appear at the top of the ASPX page, before any output. It supports five attributes (or parameters), of which two are required.
|
|
Duration |
Required Properties. The time, in seconds, that the page should be cached. Must be a positive integer. |
Location |
Specifies the location where the output should be cached. If you want to specify this parameter, you must be one of the following options: Any, Client, downstream, None, Server, or serverandclient. |
VaryByParam |
Required Properties. The name of the variable in Request, which should produce a separate cache entry. "None" means no change. "*" can be used to create a new cache entry for each different array of variables. The variables are separated by ";". |
VaryByHeader |
Changes the cache entry based on the changes in the specified header. |
VaryByCustom |
Allows you to specify custom changes in Global.asax (for example, "Browser"). |
Most cases can be handled with the combination of the required Duration and VaryByParam options.
For example, if your product catalog allows users to view catalog pages based on CategoryID and page variables, you can cache the product catalog for a period of time with a VaryByParam with a parameter value of "Categoryid;page" (if the product is not changing at any time, an hour is acceptable, Therefore, the duration is 3,600 seconds). This creates a separate cache entry for each catalog page for each category. Each entry will be maintained for one hours from its first request.
VaryByHeader and VaryByCustom are primarily used to customize the appearance or content of a page based on the client accessing the page. The same URL might need to render output for both the browser and the mobile phone client, so you need to cache different content versions for different clients. Or, the page might have been optimized for IE, but it needs to be able to completely reduce optimizations for Netscape or Opera (not just destroying the page). The latter example is very common and we will provide an example that shows how to achieve this goal:
Example: VaryByCustom used to support browser customization
For each browser to have a separate cache entry, the value of VaryByCustom can be set to "browser". This feature is already built into the cache module, and a separate page cache version is inserted for each browser name and major version.
<%@ OutputCache duration= "" "varybyparam=" None "varybycustom=" Browser "%>
To set the caching of a page declaratively using a cache configuration file
1 define the cache profile in the application's Web. config file to include the duration and VaryByParam settings in the configuration file.
The following <caching> configuration element defines a cache configuration file named Cache30Seconds, which caches the page for 30 seconds on the server.
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name= "cache30seconds" duration= "" "varybyparam=" None "/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
2 include the @ OutputCache directive in each ASP. NET page that uses the configuration file, and set the CacheProfile property to the name of the cache profile defined in the Web. config file.
The following code specifies that the page should use a cache configuration file named Cache30Seconds:
<%@ OutputCache cacheprofile= "cache30seconds"%>
2 fragment cache, user control output cache
Caching the entire page is often not feasible, because some parts of the page are customized for the user. However, other parts of the page are common to the entire application. These sections are best used for caching with fragment caches and user controls. Menus and other layout elements, especially those that are dynamically generated from the data source, should also be cached in this way. If desired, the cached control can be configured to change based on changes to its controls (or other properties) or any other changes supported by the page-level output cache. Hundreds of pages that use the same set of controls can also share cache entries for those controls, rather than keeping separate cached versions for each page.
Implement
Fragment caches use the same syntax as page-level output caches, but they apply to user controls (. ascx files) instead of Web forms (. aspx files). In addition to the Location property, user controls are also supported for all properties that OutputCache supports on a Web form. The user control also supports the OutputCache property named VaryByControl, which alters the cache of the control based on the value of the member of the user control (typically, the control on the page, for example, DropDownList). If VaryByControl is specified, the VaryByParam can be omitted. 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, which will make the cached version of the user control available to all pages that reference the control.
Example
<%@ OutputCache duration= "*" varybyparam= "*"%>
The example caches the user control for 60 seconds and creates a separate cache entry for each change to the query string, and for each page on which the control resides.
<%@ OutputCache duration= "" "varybyparam=" None "Varybycontrol=" Categorydropdownlist "%>
The example caches the user control for 60 seconds and creates a separate cache entry for each of the different values of the Categorydropdownlist control, for each page on which the control resides.
<%@ OutputCache duration= "varybyparam=" None "varybycustom=" Browser "shared=" True%>
Finally, the example caches the user control for 60 seconds, and a cache entry is created for each browser name and major version. Each browser's cache entry is then shared by all pages that reference the user control (as long as all pages refer to the control with the same ID).
3 caching API, using the cache object
Page-level and user-control-level output caching is really a quick and easy way to improve site performance, but in ASP. NET, the real flexibility and power of caching is provided through the cache object. Using the Cache object, you can store any serializable data object, based on the combination of one or more dependencies, to control how the cache entry expires. These dependencies can include the elapsed time since the item was cached, the elapsed time since the item was last accessed, changes to the file and/or folder, and changes to other cache entries, which can also include changes to specific tables in the database after a few processing.
storing Data in the Cache
The simplest way to store data in the Cache is to use a key to assign a value, just like a HashTable or Dictionary object:
cache["key"] = "value";
This practice stores the item in the cache without any dependencies, so it does not expire unless the cache engine deletes it in order to provide space for other cached data. To include specific cache dependencies, you can use the ADD () or Insert () method. Each of these methods has several overloads. The only difference between add () and insert () is that add () returns a reference to the cached object, and insert () has no return value (empty in C # and Sub in VB).
Example
Cache.Insert ("Key", Myxmlfiledata, New System.Web.Caching.CacheDependency (Server.MapPath ("Users.xml"));
This example inserts the XML data from the file into the cache without having to read from the file at a later request. The role of CacheDependency is to ensure that the cache expires immediately after a file change so that the most recent data can be fetched from the file and re-cached. If the cached data is 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 "}));
This example inserts a second block of data with a key value of "key" (depending on whether the first chunk exists). If a key named "key" does not exist in the cache, or if the item associated with the key has expired or is updated, the cache entry for "Dependentkey" expires.
Cache.Insert ("Key", Mytimesensitivedata, NULL, DateTime.Now.AddMinutes (1), TimeSpan.Zero);
Absolute expiration: This example caches data that is affected by time for one minute, and after a minute, the cache expires. Note that 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 some data that is frequently used. The data will remain in the cache until the data has not been referenced for a minute. Note that sliding expiration and absolute expiration cannot be used together.
more Options
In addition to the above mentioned dependencies, we can also specify the priority of the items (low, high, notremovable, which are The CacheItemRemovedCallback function that is called when an item in the cache expires, as defined in the System.Web.Caching.CacheItemPriority enumeration. Most of the time, the default priority is sufficient-the cache engine can complete the task normally and handle the memory management of the cache. The cacheitemremovedcallback option takes into account some very interesting possibilities, but it is rarely used in practice. However, to illustrate the method, I will provide one example of its use:
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) {Appen DLog ("The cached value with key '" + key + "' is removed from the cache. Reason: "+ Reason. ToString ()); }
The example uses the
Appendlog ()
Method (this method is not discussed here, see writing Entries to Event Logs Any logic defined in the cache to record the reason for the expiration of the data in the buffer. You can determine whether the cache is being used effectively or whether you may need to increase the memory on the server by logging these entries when items are deleted from the cache and logging the reason for deletion. Note that callback is a static (Shared in VB) method, which is recommended because if you do not use it, an instance of the class that holds the callback function remains in memory to support the callback (not necessary for the Static/shared method).
This feature has a potential use-refreshing cached data in the background so that users never have to wait for the data to be populated, but the data remains relatively new. In practice, however, this attribute does not apply to the current version of the caching API because the callback is not triggered or not completed until the cached item is removed from the cache. Therefore, the user will frequently issue a request to try to access the cached value, and then discover that the cache value is empty and have to wait for the cached value to be refilled. I want to see an additional callback in the future ASP. NET version, which can be called cacheditemexpiredbutnotremovedcallback, and if the callback is defined, execution must be completed before the cache entry is deleted.
Cached data reference mode
Whenever we try to access data in the cache, we should take into account the fact that the data may not already be in the cache. Therefore, the following pattern should generally apply to your access to 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[cacheke Y] as DataTable; if ((bypasscache) | | | (CacheItem = = null)) {CacheItem = Getcustomersfromdatasource (); Cache.Insert (CacheKey, CacheItem, NULL, DateTime.Now.AddSeconds (Getcachesecondsfromconfig (CacheKey), TimeSpan.Zero ); } return (DataTable) CacheItem; }
Here are a few things to note about this pattern:
Some values (for example, CacheKey, CacheItem, and cache duration) are defined once and defined only once.
Caching can be skipped as needed-for example, when registering a new customer and redirecting to the customer list, it might be best to skip the cache and repopulate the cache with the latest data, which includes the newly inserted customer.
The cache can only be accessed once. This practice improves performance and ensures that nullreferenceexceptions does not occur because it exists the first time it is checked, but it expires before the second check.
This mode uses strong type checking. The "as" operator in C # attempts to convert an object to a type, and returns only null (NULL) if it fails or if the object is empty.
The duration is stored in the configuration file. Ideally, all cache dependencies, whether file-based or time-based, or other types of dependencies, should be stored in the configuration file, making changes and easily measuring performance. I also recommend that you specify the default cache duration, and let the Getcachesecondsfromconfig () method use the default duration if you do not specify a duration for the cacheKey you are using.
Summary
Caching can greatly improve the performance of your application, so you should consider it when designing your application and performing performance tests on your application. Applications will always benefit more or less from caching, and of course some applications are better suited to caching than other applications. A deep understanding of the caching options provided by ASP. Is an important skill that any ASP.
Reprint to: http://blog.sina.com.cn/s/blog_67aaf4440100q4aw.html