[Entlib] how to learn from Microsoft enterprise database 5.0-Step 4: Use 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, stored procedures are not supported. Therefore, you need to customize the storage method. You can directly view the enterprise database.CodeIn the cache. database. databackingstore. CS class, a storage method is customized like 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. predictionrangeslidingexpiration);} This. itemslidingexpiration = slidingexpiration;} public slidingtime (timespan slidingexpiration, datetime originaltimestamp): This (slidingexpiration) {timelastused = originaltimestamp ;}

Extendedformattime: Specify the expiration format to expire in a specific format. Use the extendedformat. CS class to wrap the expiration method. For details, refer to extendedformat. CS,Source codeMany methods have been provided in

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:

Public static class dataaccess <t> {Private Static readonly string assemblystring = configurationmanager. appsettings ["Dal"]; // <summary> // Common Object reflection (including cache) /// </Summary> /// <Param name = "classname"> name of the class to be reflected </param> /// <returns> </returns> Public static t createobject (string classname) {var typename = assemblystring + ". "+ classname; // determines whether the object is cached. if the object is already cached, it is directly read from the cache. Otherwise, it is directly reflected and cached var OBJ = (t) cachehelper. g Etcache (typename); If (OBJ = NULL) {OBJ = (t) assembly. load (assemblystring ). createinstance (typename, true); cachehelper. add (typename, OBJ, true);} return OBJ;} public static iclassinfoservice createclassinfo () {string typename = assemblystring + ". classinfoservice "; // determines whether the object is cached. if the object is already cached, it is directly read from the cache. Otherwise, it is directly reflected and cached if (cachehelper. getcache (typename )! = NULL) {return (iclassinfoservice) cachehelper. getcache (typename);} else {iclassinfoservice service = (iclassinfoservice) assembly. load (assemblystring ). createinstance (typename, true); cachehelper. add (typename, service, true); return service ;}}

The bll layer call code is as follows:

 
Private iclassinfoservice classinfoservice = dataaccess <iclassinfoservice>. Createobject ("classinfoservice ");

Note that the cache of the enterprise database is used. If cached to the database or independent storage, the cache object must be serializable, And 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. Since Microsoft enterprise database 5.0 is the path to learning this series, I am going to introduce the modules of the enterprise database in the form of a small project, so the source code will be based on the seriesArticleSo 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

 

Index of a series of articles on the learning path of Microsoft enterprise database 5.0:

Step 1: getting started

Step 2: Use the vs2010 + data access module to create a multi-database project

Step 3: Add exception handling to the project (record to the database using custom extension)

Step 4: Use the cache to improve the website's performance (entlib caching)

Step 5: Introduce entlib. the validation module information, the implementation level of the validators, and the use of various built-in validators-step 5 of the previous article introduces entlib. validation module information, implementation level of validators, and use of various built-in validators-Part 1

Step 5: Introduce the entlib. validation module information, the implementation level of the validators, and the use of various built-in validators-Part 2

Step 6: Use the validation module for server-side data verification

Step 7: Simple Analysis of the cryptographer encryption module, custom encryption interfaces, and usage-Part 1

Step 7: Simple Analysis of the cryptographer encryption module, custom encryption interfaces, and usage-Part 2

Step 8. Use the configuration setting module and other methods to classify and manage enterprise database configuration information

Step 9: Use the policyinjection module for AOP-PART1-basic usage

Step 9: Use the policyinjection module for AOP-PART2-custom matching rule

Step 9: Use the policyinjection module for AOP-PART3 -- Introduction to built-in call Handler

Step 9: Use the policyinjection module for AOP-PART4 -- create a custom call handler to achieve user operation Logging

Step 10: Use unity to decouple your system-Part1-Why use unity?

Step 10: Use unity to decouple your system-Part2-learn how to use Unity (1)

Step 10. Use unity to decouple your system-Part2-learn how to use Unity (2)

Step 10: Use unity to decouple your system-Part2-learn how to use Unity (3)

Step 10: Use unity to decouple your system-Part3-dependency Injection

Step 10: Use unity to decouple your system-part4 -- unity & piab

Extended learning:

Extended learning and dependency injection in libraries (rebuilding Microsoft Enterprise Library) [go]

 

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.