Enterprise database-inventory module

Source: Internet
Author: User

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:

Public static class DataAccess <T> {private static readonly string assemblyString = ConfigurationManag
  
  

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

Er. 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. getCache (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");

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.