Use ASP.NET Cache to improve site performance

xiaoxiao2021-03-06  93

[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's cache prompts 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 negligence caches from getting a "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. The page-level output cache is the simplest cache form, and 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). Implementation To implement the page output cache, just 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 to customize to make each browser have a separate cache entry, VarybyCustom's value 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"%>

The clip cache, the user control output cache cache 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, select the control you need to cache as needed: (1) The properties of a control have changed (2) any page or control status changes supported by the page level output cache Once the control is cached, Use them hundreds of pages to share these controls, and no longer need to keep individual control cache versions for each page. Realizing the syntax used by the cloc 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 the user control 60 seconds and will target each different value for the CategoryDrop Downlist control, each of which The page creates a separate cache entry.

<% @ Outputcache duration = "60" VarybyParam = "none" VarybyCustom = "Browser" shared = "true"%> Finally, this example will cache the user control 60 seconds and will create one for each browser name and the main version. Cache entry. 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, using the Cache object page level and user control level output cache is indeed a way to quickly and easily increase site performance, but in ASP.NET, the true flexibility and powerful function of 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. The easiest way to store data in Cache in cache is to assign a value to it, just like a HashTable or Dictionary object: cache ["k"] = "value"; this practice will be stored in the cache Item, without any dependencies, so it doesn't expire, unless the cache engine provides space to other cache data to provide space. 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 XML data in the file into the cache, no need to request later Document read. 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 the key value "Key" Two data blocks (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 data about time a minute, after a minute, the cache will go period. 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 expire: 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 as the object in the cache CacheItemRemoveDCallback function called during expiration. 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 illustrate this 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: " REASON.TOSTRING ());} 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 complete the execution before deleting the cache item. Cache Data Reference Mode Whenever we try to access data in the cache, you should take into account a situation, 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.

转载请注明原文地址:https://www.9cbs.com/read-122753.html

New Post(0)