[Introduction]
ASP.NET provides three main forms of cache: page-level output cache, user control level output cache (or fragment cache) and cache API. The advantage of output cache and fragment cach is very easy to implement, in most cases, it is sufficient to use these two caches. The cache API provides additional flexibility (actually a considerable flexibility), which can be used to utilize the cache at each layer of the application. This paper has been introduced the application of these three cache techniques in the system layers.
In many features provided by ASP.NET, cache support is undoubtedly my most appreciated, I said that it is of course full reason. Compared to all other features of ASP.NET, the cache has the greatest potential impact on the performance of the application, using cache and other mechanisms, ASP.NET developers can accept the use of high-cost controls (for example, DataGrid) build sites. Additional expenses don't worry that performance will be too much affected. To maximize the cache in your application, you should consider how cache is achieved at all program levels.
Steve cache prompt
To cache as early as possible; often cache
You should cache every layer of the application. Cache support is added to the data layer, the business logic layer, the UI, or the output layer. Memory is now very cheap now - therefore, by achieving caches throughout the application through intelligence, it can be improved.
Cache prevents many faults
The cache is a method of obtaining "sufficiently good" performance without having a large amount of time and analysis. Here again, memory is now very cheap, so if you can get the desired performance by going to the output cache for 30 seconds, not to spend a day or even a week, you can get the desired performance, you will definitely choose a cache. Solution (assuming 30 seconds of old data). Caches are one of the features that use 20% to get 80% return, so we should improve performance and should first think of cache. However, if the design is very bad, it will eventually bring bad consequences, so you must also design the application properly as possible. But if you just need to get a high enough performance, the cache is your best choice, you can re-design the application when you have time.
Page-level output cache
As the simplest caching form, the output cache is only a copy of the HTML sent by the response request in the memory. There will then be a request to provide the output of the cache, until the cache expires, this is possible to improve significantly (depending on how much overhead is required to create the original page output - the output of the send cache is always very fast, and compare stable).
achieve
To implement a page output cache, you can add an OutputCache instruction to the page.
<% @ Outputcache duration = "60" varybyparam = "*"%>
As with other page instructions, the instruction 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 attributes. The page should be cached, in seconds. Must be positive integers.
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 is required. The name of the variable in the request, these variable names should generate a separate cache entry. "None" means there is no change. "*" Can be used to create a new cache entry for each different variable array. The variable is separated by ";".
VarybyHeader changes Cache entries based on changes in the designated header.
Varybycustom allows custom changes in Global.asax (for example, "Browser"). Most of the cases can be handled with a combination of required Duration and VarybyParam options. For example, if your product catalog allows users to view directory pages based on CategoryID and page variables, you can use the parameter value "categoryid; page" to cache the product directory for a while (if the product is not changed at any time, one hour can still Accepted, therefore, the duration is 3,600 seconds). This will create a separate cache entry for each directory page of each species. Each entry will be within an hour from its first request. VarybyHeader and VarybyCustom are used to customize the appearance or content of the page based on the client access page. The same URL may need to be output to the browser and mobile phone client, so you need to cache different content versions for different clients. Alternatively, the page may have been optimized for IE. This optimization function should be canceled for Netscape or Opera. The latter example is very common, we will provide an example of how to implement this goal:
Example: VarybyCustom is used to support browser customization
In order to make each browser have a separate cache entry, VarybyCustom's values can be set to "browser". This feature has been built into the cache module and will insert a separate page cache version for each browser name and the main version.
<% @ Outputcache duration = "60" varybyparam = "none" VarybyCustom = "browser"%>
Fragment cache, user control output cache
Caching the entire page is usually not feasible, because some parts of the page are customized for users. However, other parts of the page are all the entire application. These parts are best suited to cache segment cache and user controls. In addition, menus and other layout elements, especially those generated from data source, can also be cached in this way.
If necessary, you can select the control you need to cache as follows:
(1) The properties of a control have changed
(2) Variation of any page or control status supported by the page-level output cache
Once the control is cached, these controls can be shared using hundreds of pages, and no longer need to keep individual control cache versions for each page.
achieve
The syntax used by the clip cache is the same as the page-level output cache, but it is applied to the user control (.ascx file) instead of the web form (.aspx file). In addition to the location attribute, all properties supported on the web form are also supported for all attributes supported on the web form. The user control also supports the OutputCache property called VaryByControl, which changes the control of the control based on the value of the user control (usually the control on the page, for example, DropDownList). If VarybyControl is specified, VaryByParam can be omitted. Finally, by default, each user control on each page is individually cached. However, if a user control does not change with the page in the application, and all pages use the same name, you can set the value of the parameter shared to "True", which will enable the cache version of the user control to reference the control. All pages are used.
Example
<% @ OutputCache Duration = "60" VaryByParam = "*"%> This example will cache the user control 60 seconds and will create a separate cache entry for each change in the query string.
<% @ Outputcache duration = "60" varybyparam = "none" varybycontrol = "categorydropdownList"%>
This example will cache user controls for 60 seconds and will be for CategoryDrop
The DownList control is given to each page to create a separate cache entry for each page where this control is located.
<% @ Outputcache duration = "60" VarybyParam = "none" varybycustom = "browser" shared = "true"%>
Finally, this example will cache the user control 60 seconds and create a cache entry for each browser name and the main version. The cache entry of each browser will then share all pages referenced this user control (as long as all pages are referenced by the same ID).
Cache API, use cache objects
The page-level and user control level output cache is indeed a way to improve site performance quickly and easily, but in ASP.NET, the true flexibility and powerful function of the cache is provided through the Cache object. Using the Cache object, you can store any sequentially-sequential data objects, a combination of one or more dependencies to control the cache entries expiration. These dependencies may include time passed by a certain object being cached, the time, changes to the file or folder, and the changes to other cache objects, and the change of other cache objects can be included. Changes to a specific table in the database.
Store data in cache
The easiest way to store data in cache is to assign values to it, just like a HashTable or Dictionary object:
Cache ["Key"] = "Value";
This approach will store items in the cache, and without any dependencies, it will not expire, unless the cache engine is deleted to provide space to other cache data. To include a specific cache dependency, the add () or insert () method can be used. Each method has several overloads. The only difference between add () and INSERT () is that add () returns a reference to the cached object, and INSERT () does not return a value (empty in C #, in VB is SUB).
Example
Cache.insert ("Key", MyXMLFiledata, New System.Web.Caching.cachedependency (Server.MAppath ("Users.xml")))))
This example can insert the XML data in the file into the cache, and do not need to read from the file when requested later. The role of Cachedependency is to ensure that the cache is expired immediately after file changes so that the latest data can be extracted from the file and re-cached. If the cached data comes from a number of files, you can specify an array of file names.
Cache.insert ("DependentKey", MyDependentData, New System.Web.caching.cached "{}, new string [] {}, new string [] {" key "});
This example can be inserted into a second data block (depending on whether there is a first data block). If there is no key called "Key" in the cache, or if the object associated with the key has expired or updated, the cache entry of "dependentKey" will expire. Cache.insert ("Key", MyTimeSensitiveData, Null, DateTime.now.addminutes (1), Timespan.zero;
Absolute expiration: This example will cache the time affected data for one minute, after a minute, the cache will expire. Note that absolute expiration and scrolling expire (see below) cannot be used together.
Cache.insert ("Key", MyfrequentlyAccessedData, null, system.Web.caching.cache.noabsoluteExpiration, Timespan.fromminutes (1));
Dynamic scrolling: This example will cache some frequently used data. The data will remain in the cache, unless the data has not been referenced for one minute. Note that the dynamic scrolling expires and absolute expires cannot be used together.
more options
In addition to the dependencies mentioned above, we can also specify the priority of the item (in turn, high, notremovable, which is defined in system.web.caching.cacheitempriority enumeration) and when the object in the cache expires Calling CacheItemRemovedCallback function. Most of the time, the default priority is enough - the cache engine can complete the task and process the cache memory management. The CacheItemRemovedCallback option takes place to some interesting possibilities, but in fact it rarely. However, in order to explain the method, I will provide an example of using it:
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: " " );}
This example will use any logic defined in the appendLog () method to record the cause of the data in the cache. You can determine if you can use the cache or you may need to increase the memory on the server if you can use the cache or you may need to increase the memory on the server. Note that Callback is a static (SHARED in VB) method, it is recommended to use this method is that if it is not used, the instance of the class saved the callback function will remain in memory to support the callback (for static / shared method) There is no need to be).
This feature has a potential use of the cache data in the background so that the user will never wait for the data to be filled, but the data is always relatively new. But in fact, this feature does not apply to the current version of the cache API because the callback is not triggered or not completed before the cached item is removed from the cache. Therefore, the user will often issue a request to access the buffer value, and then find that the cache value is empty, and has to wait for the re-filled value of the caching value. I hope to see an additional callback in the future ASP.NET version, which can be called CachedItemback, if the callback is defined, you must do execution before deleting the cache item.
Cache data reference mode
Whenever we try to access data in the cache, a situation should be considered, that is, the data may not be in the cache. Therefore, the following mode should be generally applicable to your access to the cache. In this case, we assume that the cached data is a data sheet.
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
About this mode, you need to pay attention to:
1) Some values (for example, cachekey, cacheitem, and cache duration) are defined and only defined once.
2) You can skip the cache as needed - for example, when you register a new customer and redirect to the customer list, the best way maybe the cache, re-fill the cache with the latest data, which includes newly inserted customers.
3) The cache can only access it once. This approach can improve performance and make sure NullReferenceExceptions do not occur because the item exists when the item is checked, but the second check has expired.
4) This mode uses a strong type check. The "AS" operator in the C # attempts to convert objects into types, if fails or the object is empty, only return null (empty).
5) Duration is stored in the configuration file. In the ideal case, all cache dependencies (whether file-based, or time-based, or other type of dependencies) should be stored in the configuration file, so that changes can be measured and easily measured. I also recommend that you specify the default cache duration, and if you don't specify a duration for the cachekey used, the getCacheseCondsFromConfig () method uses the default duration.
Code examples related to this article (see this book example disc) are a Helper class that will handle all of the above situations, and you can write a line or two lines of code access cache data.
summary