Redis cache details, redis details

Source: Internet
Author: User

Redis cache details, redis details

Let's officially share today's article:

. Set up the Redis server and connect it with the client

. Encapsulate the cache parent class and define common methods such as Get and Set.

. Define the RedisCache cache class and execute the Get and Set methods of Redis.

. Construct a cache factory call Method

Let's share it one step at a time:

. Set up the Redis server and connect it with the client

First, let's download the Installation File ghost at this address:

Now, you can directly use the mouse to double-click the redis-server.exe application and open the redis service form (you can also download a windows Service bearer and run the redis service in windows, you don't have to worry that you won't be able to access redis every time you close the black form of the redis Service). It runs like this:

If there is a red box, it indicates that the request is successful. The default port monitored by the redis service is 6379. to modify the port or for more configuration information, find redis. conf configuration file, detailed configuration information can come here http://www.shouce.ren/api/view/a/6231

Next, open the client and connect to the server. Let's go back to the 64-bit folder directory, move the cursor to the 64-bit folder, and install the Shift key. Right-click the folder, select "Open command window here" Export-h localhost-p 6379 and press enter to access the server ,:

Let's take a look at the server form:

That's right. The client will connect to the server. You can simply execute the set and get commands on the client:

If the client needs to access the remote redis server, you only need to replace localhost with an accessible ip address. If you need more configurations such as passwords, go to the address link above;

. Encapsulate the cache parent class and define common methods such as Get and Set.

First, the code of the parent class:

Public class BaseCache: IDisposable {protected string def_ip = string. empty; protected int def_port = 0; protected string def_password = string. empty; public BaseCache () {} public virtual void InitCache (string ip = "", int port = 0, string password = "") {} public virtual bool SetCache <T> (string key, T t, int timeOutMinute = 10) where T: class, new () {return false ;} public virtual T GetCache <T> (string key) where T: class, new () {return default (T);} public virtual bool Remove (string key) {return false ;} public virtual bool FlushAll () {return false;} public virtual bool Any (string key) {return false;} public virtual void Dispose (bool isfalse) {if (isfalse) {}}// manually release public void Dispose () {this. dispose (true); // GC is not automatically released. suppressFinalize (this );}}

The methods defined here do not have much comments. For more information, I want to see the method name. This parent class mainly implements IDisposable and implements Dispose () is used to release resources and customize a public virtual void Dispose (bool isfalse) method. suppressFinalize (this); according to the official website, it means to block the automatic release of resources. If there is nothing else, continue to read the following

. Define the RedisCache cache class and execute the Get and Set methods of Redis.

First, Let's define RedisCache and MemcachedCache classes respectively (operations on memcache cache are not implemented here), inherit BaseCache, rewrite Set, and Get the following code:

/// <Summary> // Redis cache // </summary> public class RedisCache: BaseCache {public RedisClient redis = null; public RedisCache () {// read the default configuration file data here: def_ip = "172.0.0.1"; def_port = 6379; def_password = "";} # region Redis cache public override void InitCache (string ip = "", int port = 0, string password = "") {if (redis = null) {ip = string. isNullOrEmpty (ip )? Def_ip: ip; port = 0? Def_port: port; password = string. IsNullOrEmpty (password )? Def_password: password; redis = new RedisClient (ip, port, password) ;}} public override bool SetCache <T> (string key, T t, int timeOutMinute = 10) {var isfalse = false; try {if (string. isNullOrEmpty (key) {return isfalse;} InitCache (); isfalse = redis. set <T> (key, t, TimeSpan. fromMinutes (timeOutMinute);} catch (Exception ex) {} finally {this. dispose ();} return isfalse;} public override T GetCache <T> (string key) {var t = default (T); try {if (string. isNullOrEmpty (key) {return t;} InitCache (); t = redis. get <T> (key);} catch (Exception ex) {} finally {this. dispose ();} return t;} public override bool Remove (string key) {var isfalse = false; try {if (string. isNullOrEmpty (key) {return isfalse;} InitCache (); isfalse = redis. remove (key);} catch (Exception ex) {} finally {This. Dispose () ;}return isfalse;} public override void Dispose (bool isfalse) {if (isfalse & redis! = Null) {redis. dispose (); redis = null ;}# endregion} // <summary> // Memcached cache /// </summary> public class MemcachedCache: BaseCache {}

Here, the RedisClient class used is referenced by the nuget package. Here, the nuget package is:

Next, let's take a look at the rewritten InitCache method. There are some ip addresses, ports, and password parameters, which are directly written to the cs file but not read from the configuration file, you can extend the parameters. These parameters are passed through the RedisClient constructor to the underlying Socket for access. Below is a simple demonstration of the RedisClient constructor:

public RedisClient();    public RedisClient(RedisEndpoint config);    public RedisClient(string host);    public RedisClient(Uri uri);    public RedisClient(string host, int port);    public RedisClient(string host, int port, string password = null, long db = 0);

As for Get, the Set method is eventually accessed using the RedisClient object. I personally think it is worth noting that the expiration time parameter in the Set method has not been tested yet:

? These methods are used to set the expiration time. If the cache key is used at this time when the expiration time is approaching, will the expiration time automatically increase the expiration time, there is no test at the moment (this is because of the previous project. the memecache cache in the. net core framework has this setting, so should redis)

Here, we need to override the public override void Dispose (bool isfalse) method. Because the RedisClient needs to be released after it is called, we can manually release it through Dispose, instead of using ()

. Construct a cache factory call Method

Next, we need to define a cache factory, because we have defined a RedisCache and MemcachedCache. Obviously, there are multiple cache method calls, the method used to define a factory mode to call the corresponding cache. The factory mode here does not use the method for directly displaying new RedisCache (), new MemcachedCache () objects, instead, the reflection principle is used to create the corresponding cache object;

First, define an enumeration. The declared name in the enumeration should be the same as the cache class name. The Code is as follows:

public enum CacheType {  RedisCache,  MemcachedCache }

Next, define a factory to CacheRepository (Cache factory), and define the method Current as follows:

public static BaseCache Current(CacheType cacheType = CacheType.RedisCache)  {   var nspace = typeof(BaseCache);   var fullName = nspace.FullName;   var nowspace = fullName.Substring(0, fullName.LastIndexOf('.') + 1);   return Assembly.GetExecutingAssembly().CreateInstance(nowspace + cacheType.ToString(), true) as BaseCache;  }

*: Pass the enumeration parameter to determine the typeName parameter required for the reflection CreateInstance () method, so as to define the cache object to be accessed, note that a namespace nowspace is added, because the cache class and the factory class may not be in the same namespace, however, it is usually the same namespace as the cache base class. Therefore, the namespace required by the cache class is intercepted at the beginning of the method (see your project here );

*: Assembly. GetExecutingAssembly () is used to obtain the path of the current application Assembly. This avoids the need to pass the Assembly path address when using the Assembly. Load () method.

After the above requirements are met, we can call the code on the test page, for example, CacheRepository. current (CacheType. redisCache ). setCache <MoFlightSearchResponse> (keyData and value‑cached are as simple as this. You can use the redis-cli.exe client to view the cached data:

What is your effect? The overall code is given below

# Region CacheRepository cache Factory (stored in the Session by default) /// <summary> /// cache enumeration /// </summary> public enum CacheType {BaseCache, RedisCache, memcachedCache} // <summary> // cache Factory (stored in Session by default) /// </summary> public class CacheRepository {// <summary> // cache Factory (CacheKey = "SeesionKey" in the default Session storage ") /// </summary> /// <param name = "cacheType"> cache type </param> /// <returns> </returns> public static BaseCache Current (CacheType cacheType = CacheType. redisCache) {var nspace = typeof (BaseCache); var fullName = nspace. fullName; var nowspace = fullName. substring (0, fullName. lastIndexOf ('. ') + 1); return Assembly. getExecutingAssembly (). createInstance (nowspace + cacheType. toString (), true) as BaseCache; }}/// <summary> // cache base class (stored in Session by default) /// </summary> public class BaseCache: IDisposable {protected string d Ef_ip = string. empty; protected int def_port = 0; protected string def_password = string. empty; protected string CacheKey = "SeesionKey"; public BaseCache () {}/// <summary> /// get the custom SessionId // </summary> /// <param name = "key"> key: use a unique logon account </param> /// SessionId of the <returns> hash value </returns> public virtual string GetSessionId (string key) {return Md5Extend. getSidMd5Hash (key);} public virtual void InitCache (bool isReadAndWriter = true, string ip = "", int port = 0, string password = "") {} public virtual bool SetCache <T> (string key, T t, int timeOutMinute = 10, bool isSerilize = false) where T: class, new () {var isfalse = false; try {key = key ?? CacheKey; if (t = null) {return isfalse;} var session_json = JsonConvert. serializeObject (t); HttpContext. current. session. timeout = timeOutMinute; HttpContext. current. session. add (key, session_json); isfalse = true;} catch (Exception ex) {throw new Exception (ex. message);} return isfalse;} public virtual T GetCache <T> (string key = null, bool isSerilize = false) where T: class, new () {var t = Default (T); try {key = key ?? CacheKey; var session = HttpContext. current. session [key]; if (session = null) {return t;} t = JsonConvert. deserializeObject <T> (session. toString ();} catch (Exception ex) {throw new Exception (ex. message);} return t;} public virtual bool Remove (string key = null) {var isfalse = false; try {key = key ?? CacheKey; HttpContext. current. session. remove (key); isfalse = true;} catch (Exception ex) {throw new Exception (ex. message);} return isfalse ;} /// <summary> /// increase the cache time /// </summary> /// <returns> </returns> public virtual bool AddExpire (string key, int nTimeMinute = 10) {return true;} public virtual bool FlushAll () {return false;} public virtual bool Any (string key) {return false;} public Virtual bool SetHashCache <T> (string hashId, string key, T t, int nTimeMinute = 10) where T: class, new () {return false ;} public virtual List <string> GetHashKeys (string hashId) {return null;} public virtual List <string> GetHashValues (string hashId) {return null ;} public virtual T GetHashValue <T> (string hashId, string key) where T: class, new () {var t = default (T); return t;} public virtual Bool RemoveHashByKey (string hashId, string key) {return false;} public virtual void Dispose (bool isfalse) {if (isfalse) {}// manually release public void Dispose () {this. dispose (true); // GC is not automatically released. suppressFinalize (this) ;}/// <summary> // Redis cache /// </summary> public class RedisCache: BaseCache {public IRedisClient redis = null; public RedisCache () {// read the data in the default configuration file def_ip = "127.0.0.1"; def_port = 6379; def_password = "" ;}# region Redis cache public static object _ lockCache = new object (); public override void InitCache (bool isReadAndWriter = true, string ip = "", int port = 0, string password = "") {if (redis = null) {ip = string. isNullOrEmpty (ip )? Def_ip: ip; port = 0? Def_port: port; password = string. IsNullOrEmpty (password )? Def_password: password; // a single redis service // redis = new RedisClient (ip, port, password); // if the password of the cluster service is in the format of pwd @ ip: port var readAndWritePorts = new List <string> {"shenniubuxing3@127.0.0.1: 6379"}; var onlyReadPorts = new List <string> {"shenniubuxing3@127.0.0.1: 6378", "shenniubuxing3@127.0.0.1: 6377 "}; var redisPool = new PooledRedisClientManager (readAndWritePorts, onlyReadPorts, new RedisClientManagerC Onfig {AutoStart = true, // maximum read link MaxReadPoolSize = 20, // maximum write link MaxWritePoolSize = 10}) {// ConnectTimeout = 20 for each link, // connection pool timeout time PoolTimeout = 60}; lock (_ lockCache) {redis = isReadAndWriter? RedisPool. getClient (): redisPool. getReadOnlyClient () ;}} public override bool AddExpire (string key, int nTimeMinute = 10) {var isfalse = false; try {if (string. isNullOrEmpty (key) {return isfalse;} InitCache (); // isfalse = redis. expireEntryIn (key, TimeSpan. fromMinutes (nTimeMinute); isfalse = redis. expireEntryAt (key, DateTime. now. addMinutes (nTimeMinute);} catch (Exception ex) {} finally {This. dispose ();} return isfalse;} public override bool SetCache <T> (string key, T t, int timeOutMinute = 10, bool isSerilize = false) {var isfalse = false; try {if (string. isNullOrEmpty (key) {return isfalse;} InitCache (); if (isSerilize) {var data = JsonConvert. serializeObject (t); var bb = System. text. encoding. UTF8.GetBytes (data); isfalse = redis. set <byte []> (key, bb, TimeSpan. fromMinutes (TimeOutMinute);} else {isfalse = redis. set <T> (key, t, TimeSpan. fromMinutes (timeOutMinute) ;}} catch (Exception ex) {} finally {this. dispose ();} return isfalse;} public override T GetCache <T> (string key, bool isSerilize = false) {var t = default (T); try {if (string. isNullOrEmpty (key) {return t;} InitCache (false); if (isSerilize) {var bb = redis. get <byte []> (key); if (bb. length <= 0) {Return t;} var data = System. text. encoding. UTF8.GetString (bb); t = JsonConvert. deserializeObject <T> (data);} else {t = redis. get <T> (key) ;}} catch (Exception ex) {} finally {this. dispose ();} return t;} public override bool Remove (string key) {var isfalse = false; try {if (string. isNullOrEmpty (key) {return isfalse;} InitCache (); isfalse = redis. remove (key);} catch (Exception ex ){} Finally {this. dispose ();} return isfalse;} public override bool SetHashCache <T> (string hashId, string key, T t, int nTimeMinute = 10) {var isfalse = false; try {if (string. isNullOrEmpty (hashId) | string. isNullOrEmpty (key) | t = null) {return isfalse;} InitCache (); var result = JsonConvert. serializeObject (t); if (string. isNullOrEmpty (result) {return isfalse;} isfalse = redis. setEntryIn Hash (hashId, key, result); if (isfalse) {AddExpire (key, nTimeMinute) ;}} catch (Exception ex) {} finally {this. dispose ();} return isfalse;} public override List <string> GetHashKeys (string hashId) {var hashKeys = new List <string> (); try {if (string. isNullOrEmpty (hashId) {return hashKeys;} InitCache (); hashKeys = redis. getHashKeys (hashId);} catch (Exception ex) {} finally {this. dispose ();} Return hashKeys;} public override List <string> GetHashValues (string hashId) {var hashValues = new List <string> (); try {if (string. isNullOrEmpty (hashId) {return hashValues;} InitCache (); hashValues = redis. getHashValues (hashId);} catch (Exception ex) {} finally {this. dispose ();} return hashValues;} public override T GetHashValue <T> (string hashId, string key) {var t = default (T); t Ry {if (string. isNullOrEmpty (hashId) | string. isNullOrEmpty (key) {return t;} InitCache (); var result = redis. getValueFromHash (hashId, key); if (string. isNullOrEmpty (result) {return t;} t = JsonConvert. deserializeObject <T> (result);} catch (Exception ex) {} finally {this. dispose ();} return t;} public override bool RemoveHashByKey (string hashId, string key) {var isfalse = false; try {I F (string. isNullOrEmpty (hashId) | string. isNullOrEmpty (key) {return isfalse;} InitCache (); isfalse = redis. removeEntryFromHash (hashId, key);} catch (Exception ex) {} finally {this. dispose ();} return isfalse;} public override void Dispose (bool isfalse) {if (isfalse & redis! = Null) {redis. dispose (); redis = null ;}# endregion} // <summary> // Memcached cache /// </summary> public class MemcachedCache: BaseCache {}# endregion

The Redis cache I shared this time is helpful to you in terms of setting up and using it. I would like to extend my support to you. Thank you.

The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!

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.