Cache Application Block
1. Introduction
We know that there is a System in Asp.net. web. caching namespace, but there is no System in Windows Form. windows. forms. caching namespace, when we use cache in the WinForm program, System is often referenced. web. the Caching namespace uses its Caching mechanism to solve the cache problem. However, after all, it is a bit awkward to use. The cache application block came into being, but its bigger role is to cache local data in the Smart Client program to the database or other storage locations. Compared with the System. Web. Caching namespace, the cache application block provides better consistency and scalability, and can meet the cache mechanisms of WinForm applications, WinForm-Based Smart Client, Web and other applications. If cache is used in web programs, System. Web. Caching is sufficient. The key is that developers must use it consciously and use it flexibly. If you want to make the cache mechanism of the program have consistent policies, more concise calling methods, and better scalability, you still need to use the cache application block.
In daily programming, we often need:
1. We repeatedly use the same set of data, which comes from persistent devices and takes some resources and time to read. We hope to cache the data locally after obtaining it, the next read is directly read from the local memory.
2. We want to use a group of data offline. This group of data is obtained from the data source (Network, database, Webservices, etc.) and then persisted to the local device. During the next read, we should avoid reading from the data source again.
3. When the number of applications increases and the data throughput increases, the program can maintain good performance, that is, the program has scalability.
4. the cached data should be updated in a timely manner to be consistent with the data source.
The cache application block is designed for this purpose and has the following features:
1. It can be applied to various applications. Such as WinForm applications, Smart Clients, Web applications, and Enterprise Services. It can also be applied to different layers of the program architecture.
2. Flexible and variable cache Storage options. Supports isolated storage, Database, and memory, and supports seamless switching.
3. When modifying the cache policy, you do not need to modify the source code.
4. The policy can be automatically deleted after expiration. Supports time-based expiration settings and file-based expiration settings. If a time-based expiration policy is used, it can be absolute time, relative time, custom format time, and so on.
2. Procedure
① Use the configuration console to add cache application blocks.
The procedure is the same as that of other application blocks.
When a memory-based Cache Policy is used, there are several parameters to set. ExpirationPollFrequencyInSecond indicates the expiration polling cycle, that is, how long will it take to check which cache items have expired, executed by independent background processes. This parameter is critical. If the time is set too short, the background process will be continuously executed, occupying a large amount of CPU time. If the time is too long, the memory will be wasted, to find a parameter that is not long or short, we recommend that you use a performance counter to monitor it and select a moderate parameter.
After the Cache is added, the memory-based Cache is supported by default. You can also add multiple Cache managers to use different Cache policies.
② Add cache items by writing code
// The simplest way to add a Cache item: This is the simplest one. We also use it most frequently and directly create the default Cache Manager.
CacheManager cacheManager = CacheFactory. GetCacheManager ();
CacheManager. Add ("key", myObject );
// Create a specified Cache Manager
CacheManager cacheManager = CacheFactory. GetCacheManager ("Custom Manager ");
CacheManager. Add ("key", myObject );
// Cache based on absolute expiration time
// Expiration means that when the specified time is reached, the system will clear this cache item. If you access it again, it will be rebuilt.
CacheManager isolatedCacheManager = CacheFactory. GetCacheManager ("Isolated Cache Manager ");
DateTime refreshTime = new DateTime (2005, 7, 28, 17, 10, 10 );
AbsoluteTime expireTime = new AbsoluteTime (refreshTime );
IsolatedCacheManager. Add ("myKey", dataSet, CacheItemPriority. Normal, null, expireTime );
// Note that the preceding example is based on the Isolated cache of Isolated Storage. It can be seen that the Client code is written exactly the same as the Code cached by memory and database, this ensures that the Client code does not need to be modified when your cache policy changes.
// Cache with relative expiration time
TimeSpan timeSpan = new TimeSpan (0, 10, 0 );
SlidingTime expireTime = new SlidingTime (timeSpan );
CacheManager. Add ("myKey1", cachedObject, CacheItemPriority. Normal, null, expireTime );
CacheManager has only two overloaded Add methods. Its Sign is as follows:
Public void Add (string key, object value );
Public void Add (string key, object value, CacheItemPriority scavengingPriority, ICacheItemRefreshAction refreshAction, params ICacheItemExpiration [] expirations );
// Expiration settings for custom formats
// Format: <Minute> <Hour> <Day of month> <Month> <Day of week>
// For example, 3 * indicates that the instance expires every 3rd minutes.
// * 1 *** indicates every minute at every day
// 15 2 **** indicates that the expiration date is set to expire at every day.
ExtendedFormatTime expireTime = new ExtendedFormatTime ("0 1 ** 5 ");
CacheManager. Add ("key", cachedObject, CacheItemPriority. Normal, null, expireTime );
// Depends on the file expiration Mechanism
FileDependency expireNotice = new FileDependency ("file name ");
ProductsCache. Add ("key", cachedObject, CacheItemPriority. Normal, null, expireNotice );
The cache application block also provides an expiration reminder mechanism. However, you must implement the ICacheItemRefreshAction interface to perform custom operations, such as reminders, during expiration.
③ Write code to read cache items
This is basically consistent with our previous usage of System. Web. Caching.
Public BizEntry ReadBizEntryByID (string bizEntryKey)
{
BizEntry bizEntry = (Product) cache. GetData (bizEntryKey );
If (bizEntry = null)
{
// If it is executed, it indicates that the cache does not exist.
// The normal code logic here is to first create a BizEntry object
// Put this BizEntry object in the cache. Of course, this object can be left empty.
}
}
Here, the GetData () method of CacheManager is used: public object GetData (string key );
Note that forced type conversion is required here.
BizEntry bizEntry = (Product) cache. GetData (bizEntryKey );
Or
BizEntry bizEntry = cache. GetData (bizEntryKey) as BizEntry;