Caching and caching

Source: Internet
Author: User
Tags microsoft sql server 2005

Caching and caching

Typically, applications can store frequently accessed data and data that requires a large amount of processing time to be created in the memory, thus improving performance. For example, if an application uses complex logic to process a large amount of data and then returns the data as a report that is frequently accessed by the user, it is more efficient to avoid re-creating a report when the user requests data each time. Similarly, if an application contains a page that processes complex data but does not need to be updated frequently, re-creating the page on the server upon each request will result in inefficiency.

In these cases, ASP. NET uses two basic caching mechanisms to improve application performance. The first mechanism is application caching, which allows you to cache generated data, such as DataSet or custom Report Business Objects. The second mechanism is the page output cache, which saves the page processing output and reuses the saved output when the user requests the page again, instead of processing the page again.

Application Cache

The application cache provides a programming method that stores any data in the memory through key/value pairs. The application cache status is similar to that of the application. However, unlike the application state, the data in the application cache is easy to lose, that is, the data is not stored in the memory throughout the application lifecycle. The advantage of using the application cache is that ASP. NET manages the cache, which removes the items in the cache when the items expire, are invalid, or the memory is insufficient. You can also configure the application cache to notify the application when an item is removed. For more information, see cache application data.

The application cache mode is used to determine whether the specified item exists in the cache when you access it. If yes, it is used. If this item does not exist, you can re-create it and put it back into the cache. This mode ensures that the latest data is always in the cache.

Page output Cache

Page output cache stores the processed ASP. NET page content in the memory. This mechanism allows ASP. NET to send page responses to the client without having to go through the page processing lifecycle again. The page output cache is particularly useful for pages that do not change frequently but require a large amount of processing to be created. For example, if you create a webpage with large traffic to display data that does not need to be updated frequently, the page output cache can greatly improve the performance of the page. You can configure page cache for each page, or create a cache configuration file in the Web. config file. With the cache configuration file, you can use these settings on multiple pages by defining the cache settings only once.

The page output cache provides two types of page cache models: full page cache and partial page cache. The full-page cache allows you to store all the page content in the memory and use it to complete client requests. Partial-page cache allows you to cache part of the page content, while other parts are dynamic content. For more information, see cache ASP. NET page.

Partial-page cache can be replaced by control cache and cache. The control cache is also called the segment cache. This method allows information to be contained in a user control, and the user control is marked as cacheable to cache part of the page output. This method caches specific content on a page and does not cache the entire page. Therefore, you need to recreate the entire page each time. For example, if you want to create a page that displays a large amount of dynamic content (such as stock information), some of which are static content (such as weekly summary), you can place the static content in the user control, and allow caching of the content.

The cache replacement is the opposite to the control cache. This method caches the entire page, but the sections in the page are dynamic. For example, if you want to create a page that is static within a specified period of time, you can set the entire page to cache. If you add a Label control that displays the user name to the page, the Label content remains unchanged for each page refresh and each user, the name of the user who requested the page before caching the page is always displayed. However, with the cache replacement mechanism, you can configure the page to be cached, but mark individual parts of the page as non-cached. In this case, you can add Label controls to the non-cacheable section to dynamically create these controls for each user and each page request. For more information, see some sections on the cache ASP. NET page.

Cache Page Based on Request Parameters

In addition to the single version of the cache page, the ASP. NET page output cache also provides some functions to create multiple versions of different pages based on different request parameters. For more information, see multiple versions on the cache page.

Automatically remove data

ASP. NET can remove data from the cache for one of the following reasons:

  • Because the memory on the server is insufficient, it starts a process called "cleaning.
  • Because the items in the cache have expired.
  • Because the item dependency has changed.

To help manage cache items, ASP. NET notifies the application when the items are removed from the cache.

Clear

Cleaning is the process of deleting items from the cache when the memory is insufficient. If some items are not accessed for a period of time, or are marked as low-priority when added to the cache, these items are removed. ASP. NET uses the CacheItemPriority object to determine the items to be cleared first. For more information, see How to: add items to the cache.

Expired

In addition to cleanup, ASP. NET automatically removes cache items when they expire. When adding an item to the cache, you can set its expiration time as described in the following table.

Expiration type

Description

Adjustable expiration

Specifies how long an item expires after the last access. For example, you can set an item to expire 20 minutes after the last access in the cache.

Absolutely expired

Specify that an item expires at the specified time, regardless of the Access frequency. For example, you can set an item to expire at or four hours later.

Dependency

You can configure the lifetime of one of the cached items to depend on other application elements, such as a file or database. When the element on which the cache item depends is changed, ASP. NET removes the item from the cache. For example, if your website displays a report created by an application using an XML file, you can place the report in the cache, and configure it to depend on the XML file. When the XML file is changed, ASP. NET will remove the report from the cache. When the code requests the report, the code first determines whether the report is in the cache. If not, the code re-creates the report. Therefore, the latest reports are always available.

ASP. NET cache supports the dependencies described in the following table.

Dependency

Description

Key dependency

Items in the application cache are stored in key/value pairs. Key dependency items can depend on another key in the application cache. If the original item is removed, the item with the key dependency is also removed. For example, you can add a cache item named ReportsValid and then cache several reports dependent on the ReportsValid key. When the ReportsValid item is removed, all cache reports dependent on it will also be removed from the cache.

File dependency

Items in the cache depend on external files. If the file is modified or deleted, the cache item is also removed.

SQL dependency

Items in the cache depend on changes to tables in the Microsoft SQL Server 2005, SQL Server 2000, or SQL Server 7.0 database. For SQL Server 2005, items in the cache can depend on a row in the table. For more information, see cache in ASP. NET using the SqlCacheDependency class.

Aggregate Dependencies

Items in the cache by using the AggregateCacheDependency class depend on multiple elements. If any dependency item changes, it will be removed from the cache.

Custom Dependencies

You can use the dependencies created by your own code to configure items in the cache. For example, you can create a custom Web service cache dependency. When the Web Service is called to obtain a specific value, the dependency will be removed from the cache.

Notification of application cache entry Removal

When an item is removed from the application cache, you can receive a notification. For example, if there is an item that requires a large amount of processing time to be created, when the item is removed from the cache, you will receive a notification so that the item can be replaced immediately. In this way, the user does not have to wait for processing the item next time. For more information, see How to notify the application when an item is removed from the cache.

In ASP. net mvc, the Cache can be accessed from HttpContext. It is an instance of System. Web. Cache. Currently, the Cache class is used for Web applications in the company framework.

Add Cache

Cache ["CacheItem1"] = "Cached Item 1"; Cache. insert ("CacheItem2", "Cached Item 2"); // The value of CacheedItem9 is "Cached Item 9" string CachedItem9 = (string) Cache. add ("CacheItem9", "Cached Item 9", null, System. web. caching. cache. noAbsoluteExpiration, System. web. caching. cache. noSlidingExpiration, System. web. caching. cacheItemPriority. default, null );

Add items to the cache by specifying Dependencies

string[] dependencies = { "CacheItem2" };Cache.Insert("CacheItem3", "Cached Item 3",new System.Web.Caching.CacheDependency(null, dependencies));   Cache.Insert("CacheItem4", "Cached Item 4",new System.Web.Caching.CacheDependency(Server.MapPath("XMLFile.xml"))); 

Add multiple Dependencies

System.Web.Caching.CacheDependency dep1 =new System.Web.Caching.CacheDependency(Server.MapPath("XMLFile.xml"));string[] keyDependencies2 = { "CacheItem1" };System.Web.Caching.CacheDependency dep2 =new System.Web.Caching.CacheDependency(null, keyDependencies2);System.Web.Caching.AggregateCacheDependency aggDep =new System.Web.Caching.AggregateCacheDependency();aggDep.Add(dep1);aggDep.Add(dep2);Cache.Insert("CacheItem5", "Cached Item 5", aggDep);

 

 

Add an item with an expiration Policy to the cache

// The following code example adds an item with an absolute expiration time of one minute to the Cache: that is, the Cache will expire one minute after it is inserted. insert ("CacheItem6", "Cached Item 6", null, DateTime. now. addMinutes (1d), System. web. caching. cache. noSlidingExpiration );
// The following code example adds an item with an elastic expiration time of 10 minutes to the cache: that is, the cache will expire after the last 10 minutes of access, if the cache is accessed every 10 minutes, the cache will not expire. Cache. Insert ("CacheItem7", "Cached Item 7", null, System. Web. Caching. Cache. NoAbsoluteExpiration, new TimeSpan (0, 10, 0 ));

 

Add items with priority settings to the cache

// The following code example adds an item with a High priority to the Cache: Cache. insert ("CacheItem8", "Cached Item 8", null, System. web. caching. cache. noAbsoluteExpiration, System. web. caching. cache. noSlidingExpiration, System. web. caching. cacheItemPriority. high, null );

To retrieve data from the cache, specify the key to store the cache item. However, because the information stored in the cache is easy to lose, that is, the information may be removed from ASP. NET, we recommend that you first determine whether the information is cached. If not, add it to the cache again and then retrieve the item.

Retrieve the value of a cache item

string cachedString;cachedString = (string)Cache["CacheItem"];if (cachedString == null){cachedString = "Hello, World.";Cache.Insert("CacheItem", cachedString);}

 

Data in the ASP. NET cache is easy to lose, that is, it cannot be stored permanently. Data in the cache may be automatically removed for any of the following reasons:

  • The cache is full.
  • This item has expired.
  • The dependency is changed.

Explicitly delete an item from the cache

Cache.Remove("MyData1");   

Notification application when items are removed from the cache

// Add a parameter to the Add method to input a CacheItemRemovedCallback delegate, which is called when the Cache is cleared. add ("MyReport", CreateReport (), null, DateTime. maxValue, new TimeSpan (0, 1, 0), System. web. caching. cacheItemPriority. default, ReportRemovedCallback );

The definition of the delegate is as follows. CacheItemRemovedReason is an enumeration that transmits the reason why the cache is removed,

public delegate void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason);

 

In Web. Config, set the cache as follows:

<Caching> <! -- Defines global application cache settings. --> <Cache <! -- Whether to disable cache memory recovery when the computer is under memory pressure. --> DisableMemoryCollection = "false" <! -- Whether to disable cache expiration. If it is disabled, the cache item does not expire and the expired cache item is not cleared in the background. --> DisableExpiration = "false" <! -- Indicates the maximum size of private bytes of the application before the cache begins to refresh the expired items and tries to recycle the memory. This limit also includes the amount of memory used by the cache and the normal memory overhead for running the application. If it is set to zero, it indicates that ASP. NET will use its own testing method to determine when to start to recycle memory. --> PrivateBytesLimit = "0" <! -- Indicates the maximum percentage of physical memory that an application can use before the cache begins to refresh the expired items and tries to recycle the memory. This memory usage also includes the memory used by the cache and the normal memory usage of running applications. If it is set to zero, it indicates that ASP. NET will use its own testing method to determine when to start to recycle memory. --> PercentagePhysicalMemoryUsedLimit = "90" <! -- Indicates the interval between the two polling application dedicated byte memory usage. --> PrivateBytesPollTime = "00:02:00"/> <outputCache enableOutputCache = "true" enableFragmentCache = "true" sendCacheControlHeader = "true" omitVaryStar = "false"> </outputCache> <! -- Specify the output cache settings for the application range. --> <OutputCacheSettings> <outputCacheProfiles> <add name = "" enabled = "true" duration = "-1" location = "" sqlDependency = "" varyByCustom = "" varyByControl =" "varyByHeader =" "varyByParam =" "noStore =" false "/> </outputCacheProfiles> </outputCacheSettings> <! -- Specify the output cache settings that can be applied to pages in the application. --> <OutputCacheSettings> <outputCacheProfiles> <clear/> </outputCacheProfiles> </outputCacheSettings> <sqlCacheDependency enabled = "true" pollTime = "60000"> <databases> <add name = "" connectionStringName = "" pollTime = "60000"/> </databases> </sqlCacheDependency> <! -- Configure SQL cache dependencies for ASP. NET applications. --> </Caching>

 

This section focuses on application caching. Only the cache node has an impact on it.

Related Article

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.