Go deep into the system. Web. caching namespace to teach you how to hold the Cache Management (1)

Source: Internet
Author: User

This article is divided into three parts. Starting from the namespace system. Web. caching where the cache is located, we will introduce in detail the cache classes and operation methods provided by the. NET Framework. After reading this article, you will learn:

  • Article 1-how to implement simple data caching
  • Article 2-cache the data read from the file and timely update the cached data through file dependency
  • Article 3-cache the entire table in the database and timely update of cache data through database Dependencies

 

1. system. Web. caching and caching mechanismIntroduction

  System. Web. caching is the namespace used to manage the cache, and its parent space is system. Web. Therefore, cache is usually used for Web website development, including development in B/S projects.

The cache design mainly takes into account that the network bandwidth may delay data submission and re-sending. If the data is stored on the client, the user can directly read the data from the client, reduces data interaction between the client and the server, and improves program performance.

Classes in the cache namespace and their descriptions:

  • The Edit class of the cache object. Its operations include adding, deleting, modifying, and deleting cache objects.
  • Cachedependency: the dependency of the basic cache object. When the basic object changes, the cache content is updated.
  • Sqlcachedependency: the dependency of cached objects in the database. When data in the database changes, the slow content is updated.

Any cached object uses a class cache. However, when the cache changes, the dependencies between common objects and database objects are different.

Demonstrate the caching mechanism in the layer-3 structure:

  

 

Ii. Cache Management class

  1. Function Description

  The cache class is a dictionary class (key-Value Pair) that stores user-required data according to certain rules. The data types are unrestricted, and the cached data can be strings and arrays, data Tables, custom classes, and so on.

The advantage of using the cache class is that when the cached data changes, the cache class will invalidate the current cached data and re-Add the cached data, and then notify the application, timely update of report cache.

  2. syntax definition

The syntax of the cache class is defined as follows:

public sealed class Cache : IEnumerable

  

Through definition, it is found that the cache class is sealed and cannot be integrated. Besides, cache inherits the ienumerable interface and allows enumeration of data in the set.

The cache lifecycle ends when the application domain activity ends. That is to say, as long as the application domain is still active, the cache will remain, because each application domain creates a cache instance. The instance information can be obtained through the cache attribute of the httpcontext object and Page Object.

  3. Detailed explanation of the Method

The cache method mainly provides editing operations on the cache data:

  • Add add data to cache object
  • Insert inserts data items into the cache, which can be used to modify existing cache data items
  • Remove remove cached data items from the cache object
  • Get gets the specified data item from the cache object. Note that the returned data type is object and type conversion is required.
  • GetType obtains the data item type from the cache object. After determining the data type, it is convenient to convert the data type.
  • Getenumerator cyclically accesses the cached data items in the cache object. Its return type is "idictionaryenumerator"

Note the parameters of the add method. The syntax is as follows:

public object Add(
string key, object value, CacheDependency dependencies,
DateTime absoluteExpiration, TimeSpan slidingExpiration,
CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback
);

 

  • Key: the key value of the cached data item, which must be unique.
  • Value: the item to be added to the cache. It can be of any type.
  • Dependencies: indicates the cached dependency. When this item changes, it means that the cached content has expired and is removed from the cache. If no dependency exists, this value is set to null.
  • Absoluteexpiration: the time when the added object expires and is removed from the cache.
  • Slidingexpiration: the time interval between the last access to the added object and the expiration time of the object. If this value is equivalent to 20 minutes, the object will expire and be removed from the cache 20 minutes after the last access.
  • Priority: indicates the priority value for revoking the cache, which is represented by the system. Web. caching. cacheitempriority enumeration. This value is used when the cache exits the object. Data items with low priority are deleted first.
  • Onremovecallback: indicates the call time when the data object is cached and deleted. It is generally used as a notification program.

Specifically, you can only specify one expiration date and one expiration date,

If you use absolute expiration, the value of the adjustable expiration must be system. Web. caching. cache. noslidingexpiration. Disable the adjustable expiration.

Otherwise, the value of the absolute expiration must be system. Web. caching. cache. noabsoluteexpiration, and the absolute expiration is disabled.

The parameters of the insert and add methods are the same, but the insert method provides more overloading. If you do not provide a value, the value is set to the default value.

The following example demonstrates the basic usage of cache:

Public partial class _ default: system. web. UI. page {protected void page_load (Object sender, eventargs e) {cache ["League"] = "NBA"; // key and value are specified, other parameters are the default value cache ["League"] = "CBA"; // Method for updating the cache item content, same as arraylist player = new arraylist (); player. add ("johnconnor"); player. add ("Yaoming"); player. add ("kobebryant"); // use the add method to add a cache item. The key is "Player" and the value is the player object. The cache item can be set to expire for 10 minutes. The priority is normal, no callback delegate cache. add ("Player", player, null, cache. noabsoluteexpiration, timespan. fromminutes (10), cacheitempriority. normal, null); player [0] = "MichaelJordan"; cache. insert ("Player", player); // The insert method can be used to insert a cache item or update its content. Here, the simplest overload response is used. write (Cache ["Player"]. getType (). name + "</BR>"); // The GetType method can be used to obtain the type of the cache item content. write (cache. get ("League "). tostring () + "</BR>"); // get method to obtain value idictionaryenumerator mycache = cache based on the key. getenumerator (); // use the getenumerator method to traverse the cache item while (mycache. movenext () response. write (mycache. key + "</BR>"); cache. remove ("League"); // remove the cache entry whose key is "League }}

  

The arraylist is used in the Code. Do not forget to add a reference to the "system. Collections" namespace. Of course, use cache. Do not forget to add "system. Web. Caching".

  4. Attribute details

  The attributes of the cache class are mainly used to obtain basic information about cached data. Here we mainly introduce the attributes of Count and item.

Count is used to obtain the total number of cache items in the cache:

Response. Write (Cache. Count); // The total number of cache items.

Item is used to return the content of the specified item. It has already been demonstrated before. Generally, classes that inherit the "ienumerable" interface have such attributes. They are packaged using []. The usage is as follows:

Response.Write(Cache["League"]);

 

3. Typical applications for fast data cache reading

  Cache is mainly used to cache data that is frequently used and does not need to be updated frequently. We will cache a player list. For demonstration convenience, we assume that data is not read from the database, but in an arraylist object.

1. Create an ASP. NET Website in Visual Studio and name it "johnconnor. cachesample".

2. Open the default. aspx page generated by default, and add a drop-down list box and a button to the design view.

3. Switch to the Code view on the page. Do not forget to add a namespace reference.

using System.Collections;using System.Web.Caching;

4. Check whether the player list is cached in the "page_loda" event. If not, add the player list to the cache. The Code is as follows:

Protected void page_load (Object sender, eventargs e) {If (! Page. ispostback) {arraylist player = new arraylist (); player. add ("johnconnor"); player. add ("Yaoming"); player. add ("kobebryant"); If (Cache ["Player"] = NULL) // Add cache {cache if no cache is available. add ("Player", player, null, cache. noabsoluteexpiration, timespan. fromseconds (10), cacheitempriority. normal, null );}}}

  

5. In the double-click event of the button, check whether the player list is cached. If yes, the list content is displayed. If not, clear the drop-down box:

Protected void button#click (Object sender, eventargs e) {If (Cache ["Player"]! = NULL) // determine whether the cache is invalid {// If the cache is not valid, retrieve the player list cache dropdownlist1.datasource = cache ["Player"] As arraylist; dropdownlist1.databind ();} else {dropdownlist1.items. clear (); // clear the list if the cache is invalid }}

Now F5 runs the program, because we set the adjustable expiration time to 10 seconds, which means that the cache will expire after the last access time is 10 seconds.

After we click the button within the first 10 seconds, the player list will be bound to the drop-down list.

However, the drop-down list will be cleared if no action is performed in the next 10 seconds. Because the cache has expired.

 

This is the first part of Cache Management. We have introduced the system. Web. caching namespace and the usage of its cache class, but it does not involve cache dependencies.

When the actual data changes, it is very bad if the cache does not change. The next two articles will introduce how to implement real-time update of cache data through dependencies. Hope everyone can join us.

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.