C # develop WeChat portals and applications (48 ),

Source: Internet
Author: User

C # development portals and applications (48 ),

In many of our frameworks or project applications, caching can improve the response speed of the program to a certain extent and reduce the load on the server. Therefore, we have considered introducing the cache module in some places, this article introduces how to use the open-source cache framework CacheManager to implement data caching. In the development framework, some common processing needs to be applied to the cache, therefore, this article takes the framework as an example to introduce the actual usage of cache. In fact, in many of our frameworks, such as hybrid development frameworks, Web development frameworks, and Bootstrap development frameworks, this module is common.

1. cache design of the framework

In our development framework, cache serves as a layer between the database and external interfaces to provide cache Response Processing for data. The following structure shows the Cache architecture design of the Web API layer.

In cache processing, I focus on using CacheManager. This cache framework is a set builder. For more information about CacheManager, let's review my previous article 《.. NET cache framework application of CacheManager in hybrid development framework (1)-introduction and use of CacheManager

CacheManager is an open-source. Net cache framework abstraction layer developed in C # language. It is not a specific cache implementation, but it supports multiple cache providers (such as Redis and Memcached) and provides many advanced features.
The main purpose of CacheManager is to make it easier for developers to handle a variety of Complex cache scenarios. CacheManager can be used to implement multi-layer caching so that the in-process cache is before the distributed cache, only a few lines of code are required.
CacheManager is more than just an interface to unify the programming models of different cache providers. It makes it easy for us to change the cache policy in a project. It also provides more features: such as cache synchronization, concurrent updates, serial numbers, event processing, and performance computing. developers can select these features as needed.

The GitHub Source Code address of CacheManager is: Release

 

2. Integrate the CacheManager cache framework

When using the CacheManager cache, we can directly use the relevant objects for processing. First, we need to define a class to initialize the cache settings and then call it, you can use IOC to construct an object during the call, as shown in the following code: create a custom Cache Management class

/// <Summary> /// process the interface based on CacheManager /// </summary> public class CacheManager: ICacheManager {// <summary> // ICacheManager object // </summary> public ICacheManager <object> Manager {get; set ;} /// <summary> /// default constructor /// </summary> public CacheManager () {// initialize cache Manager = CacheFactory. build ("getStartedCache", settings => {settings. withSystemRuntimeCacheHandle ("handleName "). and. withRedisConfiguration ("redis", config => {config. withAllowAdmin (). withDatabase (0 ). withenderson point ("localhost", 6379 );}). withMaxRetries (100 ). withRetryTimeout (50 ). withRedisBackplane ("redis "). withRedisCacheHandle ("redis", true );});}}}

Then configure the cache information in the Autofac configuration file, as shown in the following file.

If you directly use the Autofac constructor class for processing, the code that calls the cache processing is as follows.

// Obtain the corresponding interface through the AutoFac factory to implement var cache = AutoFactory. Instatnce. Container. Resolve <ICacheManager> (); if (cache! = Null) {accountInfo = cache. manager. get (key) as AccountInfo; if (accountInfo = null) {var value = BLLFactory <Account>. instance. findByID (accountId); var item = new CacheItem <object> (key, value, ExpirationMode. absolute, TimeSpan. fromMinutes (TimeOut_Minutes); cache. manager. put (item); accountInfo = cache. manager. get (key) as AccountInfo ;}}

 

For ease of use, we can further encapsulate this helper class so that it can be called for unified processing.

/// <Summary> /// Cache Management Based on. NET CacheManager. For details, refer: http://cachemanager.michaco.net/documentation /// </Summary> public class CacheManagerHelper {// <summary> // lock the processing variable /// </summary> private static readonly object locker = new object (); /// <summary> /// create a cached key value and specify the response time range. If the response expires, the corresponding value is automatically obtained. // </summary> /// <typeparam name = "T"> Object Type </typeparam> /// <param name = "key"> key of the object </param> /// <param name = "cachePopulate"> operation for obtaining the cache value </param> /// <param name = "expiration"> invalid time range of </param> /// <param name = "mo De "> failure type </param> // <returns> </returns> public static T GetCacheItem <T> (string key, Func <T> cachePopulate, TimeSpan expiration, string region = "_", ExpirationMode mode = ExpirationMode. sliding) where T: class {CacheItem <object> outItem = null; // obtain the corresponding interface through the AutoFac factory to implement var cache = AutoFactory. instatnce. container. resolve <ICacheManager> (); if (cache! = Null) {if (cache. manager. get (key, region) = null) {lock (locker) {if (cache. manager. get (key, region) = null) {// difference between Add and Put. Add is executed only when null and true is returned, put will always replace and return True // if you add as follows, the discarded key value will be left: cache. manager. put (key, value); var value = cachePopulate (); var item = new CacheItem <object> (key, region, value, mode, expiration); cache. manager. put (item) ;}} return cache. manager. get (key, region) as T;} else {throw new ArgumentNullException ("AutoFac configuration parameter error, please check autofac. whether the definition of ICacheManager exists in config ");}}}

However, the official website has provided a TryGetOrAdd method similar to the above Code logic. The definition of this method is as follows.

TryGetOrAdd (String, String, Func <String, String, TCacheValue>, out TCacheValue)

Tries to either retrieve an existing item or add the item to the cache if it does not exist. The valueFactory will be evaluated only if the item does not exist.

Declaration
bool TryGetOrAdd(string key, string region, Func<string, string, TCacheValue> valueFactory, out TCacheValue value)
Parameters
Type Name Description
String Key

The cache key.

String Region

The cache region.

Func <String, String, TCacheValue> ValueFactory

The method which creates the value which shoshould be added.

TCacheValue Value

The cache value.

Returns
Type Description
Boolean

TrueIf the operation succeeds,FalseIn case there are too records retries or the valueFactory returns null.

Based on the definition of this parameter, we can further simplify the helper class code above.

                cache.Manager.TryGetOrAdd(key, region, (_key, _region) =>{                     var value = cachePopulate();                    var item = new CacheItem<object>(key, region, value, mode, expiration);                    return item;                }, out outItem);                return outItem as T;

The code for the entire class is as follows:

/// <Summary> /// Cache Management Based on. NET CacheManager. For details, refer: http://cachemanager.michaco.net/documentation /// </Summary> public class CacheManagerHelper {// <summary> // create a cache key value and specify the response time range, the corresponding value is automatically obtained. // </summary> /// <typeparam name = "T"> Object Type </typeparam> /// <param name = "key"> key of the object </param> /// <param name = "cachePopulate"> operation for obtaining the cache value </param> /// <param name = "expiration"> invalid time range of </param> /// <param name = "mode"> failure type </param> /// <returns> </returns> public static T GetCacheItem <T> (string key, func <T> c AchePopulate, TimeSpan expiration, string region = "_", ExpirationMode mode = ExpirationMode. sliding) where T: class {CacheItem <object> outItem = null; // obtain the corresponding interface through the AutoFac factory to implement var cache = AutoFactory. instatnce. container. resolve <ICacheManager> (); if (cache! = Null) {cache. manager. tryGetOrAdd (key, region, (_ key, _ region) =>{ var value = cachePopulate (); var item = new CacheItem <object> (key, region, value, mode, expiration); return item;}, out outItem); return outItem as T;} else {throw new ArgumentNullException ("AutoFac configuration parameter error, please check autofac. whether the definition of ICacheManager exists in config ");}}}

In this way, the code is much simpler and you do not need to control the read thread lock. The following code uses the helper class to add and obtain the cache.

/// <Summary> /// to avoid frequent Database Retrieval and speed up account information retrieval, /// you can cache account information by ID for convenient and quick use, improve efficiency. /// </Summary> public static AccountInfo GetAccountByID (string accountId) {AccountInfo accountInfo = null; # Use region. NET CacheManager cache // under normal circumstances, the access_token is valid for 7200 seconds. Here we use the cache settings as short as this time. var key = "GetAccountByID _" + accountId; accountInfo = CacheManagerHelper. getCacheItem <AccountInfo> (key, () => {return BLLFactory <Account>. instance. findByID (accountId);}, TimeSpan. fromMinutes (TimeOut_Minutes); return accountInfo ;}

Through this helper class encapsulation, we can use the helper class to cache or read data in the functions to be cached.

You can also directly use the Cache Management built by Autofac for operations, as shown in the following figure.

/// <Summary> /// Decrypt data based on the decryption algorithm provided by the applet platform /// </summary> [HttpGet] public SmallAppUserInfo Decrypt (string encryptedData, string iv, string thirdkey) {SmallAppUserInfo userInfo = null; // obtain the corresponding interface through the AutoFac factory to implement var cache = AutoFactory. instatnce. container. resolve <ICacheManager> (); if (cache! = Null) {// obtain the corresponding SessionKey var sessionkey = cache. Manager. Get (thirdkey) from the cache; if (sessionkey! = Null) {// parse user identity encryption data to obtain the complete object IBasicApi api = new BasicApi (); userInfo = api. decrypt (encryptedData, iv, sessionkey. toString () ;}} return userInfo ;}

 

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.