时间: 2016/11/13 17:06:21
从 ServiceStack.Redis V4 折腾到V3种种....,以前听说过 StackExchange。终于下定决心换!!!网上查到一个 StackExchangeHelper.cs 具体地址忘了。
发现了一个问题:不同项目不同命名空间,同一个实体反序列化时会出错,改成Json就OK了。代码如下:
using My.Log; using StackExchange.Redis; using System; 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 { ////// /// public static class RedisHelper { private static readonly string Coonstr = ConfigurationManager.ConnectionStrings["RedisExchangeHosts"].ConnectionString; private static object _locker = new Object(); private static ConnectionMultiplexer _instance = null; /// /// 返回已连接的实例, /// public static ConnectionMultiplexer Instance { get { if (_instance == null) { lock (_locker) { if (_instance == null || !_instance.IsConnected) { _instance = ConnectionMultiplexer.Connect(Coonstr); } } } //注册如下事件 _instance.ConnectionFailed += MuxerConnectionFailed; _instance.ConnectionRestored += MuxerConnectionRestored; _instance.ErrorMessage += MuxerErrorMessage; _instance.ConfigurationChanged += MuxerConfigurationChanged; _instance.HashSlotMoved += MuxerHashSlotMoved; _instance.InternalError += MuxerInternalError; return _instance; } } static RedisHelper() { } /// /// 获取一个连接实例 /// /// public static IDatabase GetDatabase() { return Instance.GetDatabase(); } /// /// 过期时间 /// /// 分钟 /// private static TimeSpan ExpireTimeSpan(double Min) { bool bl = bool.Parse(ConfigurationManager.AppSettings["UseRedis"]); if (bl) { return TimeSpan.FromMinutes(Min); } else { return TimeSpan.FromMilliseconds(1); } } /// /// 清除 包含特定字符的所有缓存 /// public static void RemoveSpeStr(string keyStr) { List<string> listKeys = GetAllKeys(); foreach (string k in listKeys) { if (k.Contains(keyStr)) { Remove(k); } } } /// /// 判断在缓存中是否存在该key的缓存数据 /// /// /// public static bool Exists(string key) { return GetDatabase().KeyExists(key); //可直接调用 } /// /// 移除指定key的缓存 /// /// /// public static bool Remove(string key) { if (Exists(key)) { return GetDatabase().KeyDelete(key); } return false; } /// /// Set /// /// 类型 /// 键 /// 值 /// 多少分钟后过期 /// public static bool Set (string key, T t, double minOut = 60*3) { return GetDatabase().StringSet(key, Serialize(t), ExpireTimeSpan(minOut)); } /// /// Get /// /// /// /// public static T Get (string key) { return Deserialize (GetDatabase().StringGet(key)); } /// /// DataSet 缓存 /// public static bool SetData(string key, DataSet ds, double minOut = 60*3) { return GetDatabase().StringSet(key, Serialize(ds), ExpireTimeSpan(minOut)); } /// /// 获取 DataSet /// public static DataSet GetDataSet(string key) { return Deserialize (GetDatabase().StringGet(key)); } /// /// 刷新缓存 /// 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 } /// /// 得到所有缓存键值 /// /// 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; } //---------------------------------------------------------------------------------------------------------- static string JsonSerialize(object o) { if (o == null) { return null; } return JsonConvert.SerializeObject(o); } static T JsonDeserialize (string json) { if (json == null) { return default(T); } return JsonConvert.DeserializeObject (json); } /// /// 序列化对象 /// /// /// 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; } } /// /// 反序列化对象 /// /// /// /// static T Deserialize (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; } } /// /// 配置更改时 /// /// /// private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e) { LogHelper.LogExceRun("Configuration changed: " + e.EndPoint, new Exception()); } /// /// 发生错误时 /// /// /// private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e) { LogHelper.LogExceRun("ErrorMessage: " + e.Message, new Exception()); } /// /// 重新建立连接之前的错误 /// /// /// private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e) { LogHelper.LogExceRun("ConnectionRestored: " + e.EndPoint, new Exception()); } /// /// 连接失败 , 如果重新连接成功你将不会收到这个通知 /// /// /// private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e) { LogHelper.LogExceRun("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)), new Exception()); } /// /// 更改集群 /// /// /// private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e) { LogHelper.LogExceRun("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint, new Exception()); } /// /// redis类库错误 /// /// /// private static void MuxerInternalError(object sender, InternalErrorEventArgs e) { LogHelper.LogExceRun("InternalError:Message" + e.Exception.Message, new Exception()); } /// /// GetServer方法会接收一个EndPoint类或者一个唯一标识一台服务器的键值对 /// 有时候需要为单个服务器指定特定的命令 /// 使用IServer可以使用所有的shell命令,比如: /// DateTime lastSave = server.LastSave(); /// ClientInfo[] clients = server.ClientList(); /// 如果报错在连接字符串后加 ,allowAdmin=true; /// /// public static IServer GetServer(string host, int port) { IServer server = Instance.GetServer(host, port); return server; } /// /// 获取全部终结点 /// /// public static EndPoint[] GetEndPoints() { EndPoint[] endpoints = Instance.GetEndPoints(); return endpoints; } } }