using Lskj.Business.Impl; using Microsoft.Win32; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Runtime.Serialization; using System.Text; namespace Lskj.Redis { public static class RedisHelper { //private static readonly string ConnectionWriteString = "127.0.0.1:6379"; private static readonly string ConnectionWriteString = "127.0.0.1:6379,abortConnect=false"; private static readonly string RedisCmdStartPath = Environment.CurrentDirectory + "\\Redis"; private static IConnectionMultiplexer ConnMultiplexer; private static IDatabase Database; private static int DbIndex = 0; /// /// 刷新数据键的集合 /// private static readonly string RefRedisRefKeys = "defaultRedisRefKeys"; public static bool InitRedis(int dbIndex) { bool rtn = false; Process process = new Process(); try { process.StartInfo.FileName = "cmd.exe "; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.StartInfo.WorkingDirectory = RedisCmdStartPath; process.Start(); process.StandardInput.WriteLine("redis-server.exe --service-install redis.windows.conf --loglevel verbose"); process.StandardInput.WriteLine("redis-server --service-start"); process.StandardInput.Close(); process.StandardOutput.ReadToEnd(); if (ConnMultiplexer != null) { ConnMultiplexer.Dispose(); ConnMultiplexer = null; } if (Database != null) { Database = null; } ConnMultiplexer = ConnectionMultiplexer.Connect(ConnectionWriteString); Database = ConnMultiplexer.GetDatabase(dbIndex);//参数为创建的数据库的位置 rtn = true; } catch (Exception) { rtn = false; } finally { process.Close(); } return rtn; } public static void ClearRedis() { Process process = new Process(); try { process.StartInfo.FileName = "cmd.exe "; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.StartInfo.WorkingDirectory = RedisCmdStartPath; process.Start(); process.StandardInput.WriteLine("redis-cli.exe -h 127.0.0.1 -p 6379"); string selectOrder = string.Format("select {0}", DbIndex + ""); process.StandardInput.WriteLine(selectOrder); process.StandardInput.WriteLine("flushdb"); process.StandardInput.Close(); process.StandardOutput.ReadToEnd(); } catch (Exception) { } finally { process.Close(); } } /// /// 设置 key 并保存字符串(如果 key 已存在,则覆盖值) /// /// 名称 /// 值 /// 时间 /// public static bool StringSet(string redisKey, string redisValue, TimeSpan? expiry = null) { return Database.StringSet(redisKey, redisValue, expiry); } /// /// 获取字符串 /// /// 名称 /// 时间 /// public static string StringGet(string redisKey, TimeSpan? expiry = null) { return Database.StringGet(redisKey); } /// /// 存储一个对象(该对象会被序列化保存) /// /// 名称 /// 值 /// 时间 /// public static bool SetValue(string redisKey, T redisValue, TimeSpan? expiry = null) { bool rtn = false; try { System.IO.MemoryStream ms = new System.IO.MemoryStream();//创建内存流对象 IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(ms, redisValue);//把Datatable对象序列化到内存流 byte[] tabBuffer = ms.ToArray();//把内存流对象写入字节数组 ms.Close();//关闭内存流对象 ms.Dispose();//释放资源 rtn = Database.StringSet(redisKey, tabBuffer, expiry); } catch (Exception) { rtn = false; } return rtn; } /// /// 获取一个对象(会进行反序列化) /// /// 名称 /// 时间 /// public static T GetValue(string redisKey, TimeSpan? expiry = null) { try { byte[] buffer = Database.StringGet(redisKey); if (buffer == null) { return default(T); } else { using (System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer)) { stream.Position = 0; IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); object rtnObj = formatter.Deserialize(stream); T rtn = (T)Convert.ChangeType(rtnObj, typeof(T)); return rtn; } } } catch (Exception) { return default(T); } } /// /// 判断key是否存在 /// /// public static bool ContainKey(string key) { bool rtn = false; try { rtn = Database.KeyExists(key); } catch (Exception) { rtn = false; } return rtn; } /// /// 添加键至刷新字典 /// public static void SetRefKeyDic(string moudleid, string formkey) { string onlyOneKey = string.Format("{0}^{1}", moudleid, formkey); string mainModleId = Lskj.Model.ERPInfo.Instance.selectFormModleId; if (string.IsNullOrEmpty(mainModleId)) return; Dictionary> keyValues = GetValue>>(RefRedisRefKeys); if (keyValues == null) { keyValues = new Dictionary>(); } if (keyValues.ContainsKey(mainModleId)) { List moudleIds = keyValues[mainModleId]; if (!moudleIds.Contains(onlyOneKey)) { moudleIds.Add(onlyOneKey); } } else { List moudleIds = new List(); moudleIds.Add(onlyOneKey); keyValues.Add(mainModleId, moudleIds); } SetValue>>(RefRedisRefKeys, keyValues); } /// /// 刷新缓存数据源 /// public static void RefRedisData(string mainModleid) { Dictionary> keyValues = GetValue>>(RefRedisRefKeys); if (keyValues == null) { keyValues = new Dictionary>(); } if (keyValues.ContainsKey(mainModleid)) { System.Threading.Thread thread = new System.Threading.Thread(() => { List moudleIdsList = keyValues[mainModleid]; foreach (string onlyOneKey in moudleIdsList) { if (!ContainKey(onlyOneKey)) continue; Dictionary sqlAndDataTable = RedisHelper.GetValue>(onlyOneKey); if (sqlAndDataTable != null && sqlAndDataTable.Count > 0) { string sourceSql = sqlAndDataTable.First().Key; if (!string.IsNullOrEmpty(sourceSql)) { DataTable dataTable = BaseImpl.GetDataTableResult(sourceSql); sqlAndDataTable[sourceSql] = dataTable; RedisHelper.SetValue>(onlyOneKey, sqlAndDataTable); } } } }); thread.IsBackground = true; thread.Start(); } } /// /// 根据key删除redis数据 /// /// public static void DeleteByKey(string key) { Database.KeyDelete(key); } /// /// 切换数据库 /// /// public static void ChangeRedisDataBase(int dbIndex) { Database = ConnMultiplexer.GetDatabase(dbIndex);//参数为创建的数据库的位置 DbIndex = dbIndex; } } }