StackExchange. Redis RedisHelper. cs, stackexchange. redis

Source: Internet
Author: User

StackExchange. Redis RedisHelper. cs, stackexchange. redis

From ServiceStack. Redis V4 to V3, I have heard of StackExchange before. Finally, I made up my mind to change it !!! I found a StackExchangeHelper. cs address on the Internet and forgot it.

One problem is found: Different namespaces of different projects may encounter an error in deserialization of the same object. If it is changed to Json, it will be OK. The Code is as follows:

Using My. log; using StackExchange. redis; using System. collections. generic; using System. configuration; using System. data; using System. IO; using System. linq; using System. net; using System. runtime. serialization. formatters. binary; using Newtonsoft. json; namespace My. redis {// <summary> ///// </summary> public static class RedisHelper {private static readonly string Coonstr = ConfigurationMana Ger. connectionStrings ["RedisExchangeHosts"]. connectionString; private static object _ locker = new Object (); private static ConnectionMultiplexer _ instance = null; // <summary> // return the connected instance, /// </summary> public static ConnectionMultiplexer Instance {get {if (_ instance = null) {lock (_ locker) {if (_ instance = null |! _ Instance. isConnected) {_ instance = ConnectionMultiplexer. connect (Coonstr) ;}}// register the following Event _ instance. connectionFailed + = MuxerConnectionFailed; _ instance. connectionRestored + = MuxerConnectionRestored; _ instance. errorMessage + = MuxerErrorMessage; _ instance. configurationChanged + = MuxerConfigurationChanged; _ instance. hashSlotMoved + = MuxerHashSlotMoved; _ instance. internalError + = MuxerInternalError; Return _ instance ;}} static RedisHelper () {}/// <summary> /// obtain a connection instance /// </summary> /// <returns> </returns> public static IDatabase GetDatabase () {return Instance. getDatabase ();} /// <summary> /// expiration time /// </summary> /// <param name = "Min"> minutes </param> /// <returns> </returns> private static TimeSpan ExpireTimeSpan (double Min) {bool bl = bool. parse (ConfigurationManager. appSettings ["UseRedis"] ); If (bl) {return TimeSpan. fromMinutes (Min);} else {return TimeSpan. fromMilliseconds (1) ;}/// <summary> /// clear all caches containing specific characters /// </summary> public static void RemoveSpeStr (string keyStr) {List <string> listKeys = GetAllKeys (); foreach (string k in listKeys) {if (k. contains (keyStr) {Remove (k );}}} /// <summary> /// determine whether the cached data of this key exists in the cache. // </summary> /// <param name = "key"> </ param> // <ret Urns> </returns> public static bool Exists (string key) {return GetDatabase (). keyExists (key ); // you can call it directly} // <summary> // remove the cache of the specified key /// </summary> /// <param name = "key"> </ param> // <returns> </returns> public static bool Remove (string key) {if (Exists (key) {return GetDatabase (). keyDelete (key) ;}return false ;} /// <summary> /// Set /// </summary> /// <typeparam name = "T"> type </typeparam> /// <par Am name = "key"> key </param> /// <param name = "t"> value </param> /// <param name = "timeout"> expired in minutes </param> /// <returns> </returns> public static bool Set <T> (string key, T t, double minOut = 60*3) {return GetDatabase (). stringSet (key, Serialize (t), ExpireTimeSpan (minOut ));} /// <summary> /// Get /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name =" key "> </param> // <returns> </returns> public Static T Get <T> (string key) {return Deserialize <T> (GetDatabase (). stringGet (key);} // <summary> // DataSet cache // </summary> public static bool SetData (string key, DataSet ds, double minOut = 60*3) {return GetDatabase (). stringSet (key, Serialize (ds), ExpireTimeSpan (minOut ));} /// <summary> /// get DataSet /// </summary> public static DataSet GetDataSet (string key) {return Deserialize <DataSet> (GetDatabase (). stringGet (key);} // <summary> // refresh cache // </summary> public static void FlushAll () {var endpoints = Instance. getEndPoints (); var server = Instance. getServer (endpoints. first (); server. flushDatabase (); // to wipe a single database, 0 by default // server. flushAllDatabases (); // to wipe all databases} // <summary> /// obtain all cache key values /// </summary> /// <returns> </returns> public static List <string> GetAllKeys () {List <string> lstKey = new List <string> (); var endpoints = Instance. getEndPoints (); var server = Instance. getServer (endpoints. first (); var keys = server. keys (); foreach (var key in keys) {lstKey. add (key) ;}return lstKey ;}// jsonstatic string JsonSerialize (object o) {If (o = null) {return null;} return JsonConvert. serializeObject (o);} static T JsonDeserialize <T> (string json) {if (json = null) {return default (T);} return JsonConvert. deserializeObject <T> (json );} /// <summary> /// serialize the object /// </summary> /// <param name = "o"> </param> /// <returns> </returns> static byte [] Serialize (object o) {if (o = null) {return null;} BinaryFormatter binaryFormatter = New BinaryFormatter (); using (MemoryStream memoryStream = new MemoryStream () {binaryFormatter. serialize (memoryStream, o); byte [] objectDataAsStream = memoryStream. toArray (); return objectDataAsStream ;}} /// <summary> /// deserialization object /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "stream"> </param> // <returns> </returns> static T Deserialize <T> (byte [] stream) {if (stream = Null) {return default (T);} BinaryFormatter binaryFormatter = new BinaryFormatter (); using (MemoryStream memoryStream = new MemoryStream (stream) {T result = (T) binaryFormatter. deserialize (memoryStream); return result ;}} /// <summary> /// when the configuration is changed /// </summary> /// <param name = "sender"> </param> /// <param name = "e"> </param> private static void MuxerConfigurationChanged (object sender, endPointEven TArgs e) {LogHelper. logExceRun ("Configuration changed:" + e. endPoint, new Exception ());} /// <summary> /// when an error occurs /// </summary> /// <param name = "sender"> </param> /// <param name = "e"> </param> private static void MuxerErrorMessage (object sender, redisErrorEventArgs e) {LogHelper. logExceRun ("ErrorMessage:" + e. message, new Exception ();} // <summary> // error before the connection is re-established /// </summary> /// <param n Ame = "sender"> </param> // <param name = "e"> </param> private static void MuxerConnectionRestored (object sender, ConnectionFailedEventArgs e) {LogHelper. logExceRun ("ConnectionRestored:" + e. endPoint, new Exception ();} // <summary> // connection failed, if the connection is successfully reconnected, you will not receive this notification /// </summary> /// <param name = "sender"> </param> /// <param name =" e "> </param> private static void MuxerConnectionFailed (object sender, co NnectionFailedEventArgs e) {LogHelper. LogExceRun ("reconnect: Endpoint failed:" + e. EndPoint + "," + e. FailureType + (e. Exception = null? "": ("," + E. exception. message), new Exception ());} /// <summary> /// change the cluster /// </summary> /// <param name = "sender"> </param> /// <param name = "e"> </param> private static void MuxerHashSlotMoved (object sender, hashSlotMovedEventArgs e) {LogHelper. logExceRun ("HashSlotMoved: NewEndPoint" + e. newEndPoint + ", OldEndPoint" + e. oldEndPoint, new Exception ());} /// <summary> // redis class library error // </summary> /// <param name = "sender"> </param> // <param name = "e"> </param> private static void MuxerInternalError (object sender, internalErrorEventArgs e) {LogHelper. logExceRun ("InternalError: Message" + e. exception. message, new Exception ());} /// <summary> /// the GetServer method receives an EndPoint class or a key-value pair that uniquely identifies a server. // sometimes you need to specify a specific command for a single server // /use IServer to use all shell commands, for example: // DateTime lastSave = server. lastSave (); // ClientInfo [] clients = server. clientList (); // if an error is reported after the connection string is added, allowAdmin = true; /// </summary> /// <returns> </returns> public static IServer GetServer (string host, int port) {IServer server = Instance. getServer (host, port); return server ;} /// <summary> /// obtain all endpoints /// </summary> /// <returns> </returns> public static EndPoint [] GetEndPoints () {EndPoint [] endpoints = Instance. getEndPoints (); return endpoints ;}}}

 

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.