Microsoft enterprise database 5.0 learning path-Step 4: Using Cache to improve website performance (entlib caching)

Source: Internet
Author: User
Tags website performance

In the previous course of studying the enterprise database, I used data access to build multi-database access and use exception handle + logging to record system exceptions. Today, I will introduce how to apply the caching module in the Enterprise Library in this project.

First, you need to learn about the caching Application Block of the enterprise database:

1,Four caching MethodsIn the caching Application Block, the following four methods are provided to store cached data: memory storage (default) and independent storage (isolated storage) database cache storage and custom storage ).

2,Multiple Storage MethodsAside from custom storage, memory storage is the most basic cache. It only caches data into the memory. Although it is fast, it cannot be persistently stored, independent storage and database storage are stored on a local disk (Different storage locations depending on the Operating System) And the other is stored in the database (Convenient distributed cache), So persistent storage is not lost because of Shutdown (yes. Find the script for installation under entlib50src \ blocks \ caching \ SRC \ database \ scripts)

3,Excellent usabilityAlthough the cache class has been provided in the. NET class library system. web, it is only applicable to the console, winform, web, and service.

4,SecurityThe cache module in the enterprise database can be well integrated with the encryption module. When applicable to database caching, independent storage, or custom storage, the encryption module can be used to encrypt cached data, however, data stored in the memory cannot be encrypted.

 

After learning about the basic knowledge of caching, we can start to perform specific operations.

I am using the cache module to cache the object instances at the Dal layer of the specific database reflected in the project. This eliminates the need to reflect the object instances at the underlying layer each time, and only needs to cache the instances after 1st reflection requests, later access is directly read from the cache, which increases the access speed.

Add a caching Settings Using the enterprise database configuration tool

Here, the default settings are used, which are saved to the memory. The default settings are used for the expiration polling time, maximum storage quantity, and removal quantity.

If you do not want to use the default memory storage, you can create an independent storage or database storage.

Here, we need to mention that the database storage of the cache module of the enterprise database uses stored procedures for interaction between the cache and the database. However, this project uses multiple databases, such as SQLite, therefore, you need to customize the storage method. You can directly view the cache in the Enterprise Library code. database. databackingstore. CS class, a storage method customized in the same way as the databackingstore class, except that SQL statements are used for database interaction.

Back to the topic, I wrote a simple cachehelper to operate on the cache, And I customized a cache refresh operation class (this class must be serializable ), used to add expired objects to the cache. The Code is as follows:

Using system; using system. collections. generic; using system. LINQ; using system. text; using Microsoft. practices. enterpriselibrary. caching; using Microsoft. practices. enterpriselibrary. caching. expirations; using Microsoft. practices. enterpriselibrary. common. configuration; namespace entlibstudy. helper {public static class cachehelper {// two methods for creating cachemanager // icachemanager cache = enterpriselibrarycontainer. current. getinstance <icachemanager> (); Private Static icachemanager cache = cachefactory. getcachemanager (); /// <summary> /// add cache /// </Summary> /// <Param name = "key"> key </param> /// <Param name = "value"> value </param> // <Param name = "isrefresh"> whether to refresh </param> Public static void add (string key, object value, bool isrefresh = false) {If (isrefresh) {// custom refresh method. If it expires, it is automatically reloaded and the cache expires for 5 minutes. add (Key, value, cacheitempriority. normal, new mycacheitemrefreshaction (), new absolutetime (timespan. fromminutes (5);} else {cache. add (Key, value );}} /// <summary> /// obtain the cache object /// </Summary> /// <Param name = "key"> key </param> /// <returns> </returns> Public static object getcache (string key) {return cache. getdata (key );} /// <summary> /// remove the cache object /// </Summary> /// <Param name = "key"> key </param> Public static void removecache (string key) {cache. remove (key) ;}//< summary> /// custom cache refresh operation /// </Summary> [serializable] public class mycacheitemrefreshaction: icacheitemrefreshaction {# region icacheitemrefreshaction member /// <summary> /// custom refresh operation /// </Summary> /// <Param name = "removedkey"> key to remove </param> /// <Param name = "expiredvalue"> expired value </param> /// <Param name = "removalreason"> reason for removal </param> void icacheitemrefreshaction. refresh (string removedkey, object expiredvalue, cacheitemremovedreason removalreason) {If (removalreason = cacheitemremovedreason. expired) {icachemanager cache = cachefactory. getcachemanager (); cache. add (removedkey, expiredvalue) ;}# endregion }}

1,Cache levelIn the cache module of the enterprise database, four cache levels are provided:Low,Normal,HighAndNotremovableAfter the maximum number of cached objects is exceeded, the objects are automatically removed based on the cache level.

2,IcacheitemrefreshactionThis interface is used to facilitate expansion and use by developers. developers can perform corresponding operations after the object expires Based on the reason for removal, in which cacheitemremovedreason points

Expired: Expired removed

Removed: Removed manually

Scavenged: Because the number of caches is full, lower-level caches are removed based on the cache level.

Unknown: Unknown removal, not recommended

3,Expiration MethodThe Enterprise Library provides four expiration methods by default.

Absolutetime: It is definitely a Time Expiration. It expires when a time object is passed.

Slidingtime: The cache expires after the last access. The default value is 2 minutes. Two constructors can specify an expiration time or an expiration time and a last use time.

public SlidingTime(TimeSpan slidingExpiration){   // Check that expiration is a valid numeric value   if (!(slidingExpiration.TotalSeconds >= 1))   {      throw new ArgumentOutOfRangeException("slidingExpiration",                                       Resources.ExceptionRangeSlidingExpiration);      }      this.itemSlidingExpiration = slidingExpiration;    }public SlidingTime(TimeSpan slidingExpiration, DateTime originalTimeStamp) : this(slidingExpiration){      timeLastUsed = originalTimeStamp; }  

Extendedformattime: Specify the expiration format and use a specific format to expire. Use the extendedformat. CS class to wrap the expiration method. For details, refer to extendedformat. cs. Many methods have been provided in the source code.

Filedependency: Dependent on file expiration. expired when the dependent file is modified,I think this is very useful, because many websites, such as forums and news systems, require a lot of configuration. You can cache the configuration file information and set the dependency as a configuration file, in this way, after you change the configuration file, you can use icacheitemrefreshaction. refresh can be automatically recached.

After introducing the relevant cache parameters, let's take a look at how to use them. I have modified the original dataaccess class again, because I think if I add another data table each time, it is inconvenient for the corresponding factory to write another reflection method, so it is modified to a generic class (with the original reflection code attached, it is better to compare the method below ), when calling The bll layer, you only need to pass the interface to be converted. The Code is as follows:

Using system; using system. collections. generic; using system. LINQ; using system. text; using Microsoft. practices. enterpriselibrary. caching; using Microsoft. practices. enterpriselibrary. caching. expirations; using Microsoft. practices. enterpriselibrary. common. configuration; namespace entlibstudy. helper {public static class cachehelper {// two methods for creating cachemanager // icachemanager cache = enterpriselibrarycontainer. current. getinstance <icachemanager> (); Private Static icachemanager cache = cachefactory. getcachemanager (); /// <summary> /// add cache /// </Summary> /// <Param name = "key"> key </param> /// <Param name = "value"> value </param> // <Param name = "isrefresh"> whether to refresh </param> Public static void add (string key, object value, bool isrefresh = false) {If (isrefresh) {// custom refresh method. If it expires, it is automatically reloaded and the cache expires for 5 minutes. add (Key, value, cacheitempriority. normal, new mycacheitemrefreshaction (), new absolutetime (timespan. fromminutes (5);} else {cache. add (Key, value );}} /// <summary> /// obtain the cache object /// </Summary> /// <Param name = "key"> key </param> /// <returns> </returns> Public static object getcache (string key) {return cache. getdata (key );} /// <summary> /// remove the cache object /// </Summary> /// <Param name = "key"> key </param> Public static void removecache (string key) {cache. remove (key) ;}//< summary> /// custom cache refresh operation /// </Summary> [serializable] public class mycacheitemrefreshaction: icacheitemrefreshaction {# region icacheitemrefreshaction member /// <summary> /// custom refresh operation /// </Summary> /// <Param name = "removedkey"> key to remove </param> /// <Param name = "expiredvalue"> expired value </param> /// <Param name = "removalreason"> reason for removal </param> void icacheitemrefreshaction. refresh (string removedkey, object expiredvalue, cacheitemremovedreason removalreason) {If (removalreason = cacheitemremovedreason. expired) {icachemanager cache = cachefactory. getcachemanager (); cache. add (removedkey, expiredvalue) ;}# endregion }}

The bll layer call code is as follows:

public SlidingTime(TimeSpan slidingExpiration){   // Check that expiration is a valid numeric value   if (!(slidingExpiration.TotalSeconds >= 1))   {      throw new ArgumentOutOfRangeException("slidingExpiration",                                       Resources.ExceptionRangeSlidingExpiration);      }      this.itemSlidingExpiration = slidingExpiration;    }public SlidingTime(TimeSpan slidingExpiration, DateTime originalTimeStamp) : this(slidingExpiration){      timeLastUsed = originalTimeStamp; }  

It should be noted that because the cache of the enterprise database is used, if the cache to the database or independent storage must require that the cached object be sequential, the cache in the memory is not required, the cached objects on my side are specific operation classes in the Dal layer. Therefore, if you want to change them to non-memory storage, you need to add the [serializable] feature to the operation class.

In this way, you do not need to modify the dataaccess class in the factory after adding a new table.

The above are some basic applications of caching in this project. Due to the limited level, some advanced applications of caching cannot be proposed for the moment. Please forgive me.

For related cache module configurations, you can view the cache module written by huangcong (preliminary). For more information, see the design purpose of the cache written by virusswb.

 

Note:

1. The MSSQL database is in the database directory (you need to attach the database yourself), and The SQLite database is in the app_data directory of the web directory. Because of the project size, the bin directory of each project has been deleted, if a project cannot be generated, add the DLL of the relevant enterprise library.

2. As Microsoft enterprise database 5.0 is a learning path, this series is intended to introduce the modules of the enterprise database in the form of a small project, so the source code will be updated according to the updates in the series of articles, therefore, the source code cannot be the same as the Code posted in the article.

3. The project development environment is vs2010 + sql2005.

4. Administrator Account: Admin

Password: Admin

Source code: Click to download

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.