RedisHelper.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. 
  2. using Newtonsoft.Json;
  3. using StackExchange.Redis;
  4. using System;
  5. using System.Collections.Concurrent;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Text;
  11. namespace OASystem.Infrastructure.Tools
  12. {
  13. #region MyRegion
  14. //**************操作记录******************
  15. //内容描述:Redis帮助类
  16. //***************************************
  17. //public static class RedisHelper
  18. //{
  19. // private static string _strConn = "132.232.92.186:6379";
  20. // private static string _strPwd = "";
  21. // private static int _strDb = -1;
  22. // static ConnectionMultiplexer _redis;
  23. // static readonly object _locker = new object();
  24. // #region 单例模式
  25. // public static ConnectionMultiplexer Manager
  26. // {
  27. // get
  28. // {
  29. // if (_redis == null)
  30. // {
  31. // lock (_locker)
  32. // {
  33. // if (_redis != null) return _redis;
  34. // _redis = GetManager();
  35. // return _redis;
  36. // }
  37. // }
  38. // return _redis;
  39. // }
  40. // }
  41. // private static ConnectionMultiplexer GetManager(string connectionString = null)
  42. // {
  43. // if (string.IsNullOrEmpty(connectionString))
  44. // {
  45. // connectionString = _strConn;
  46. // }
  47. // var options = ConfigurationOptions.Parse(connectionString);
  48. // options.Password = _strPwd;
  49. // return ConnectionMultiplexer.Connect(options);
  50. // }
  51. // #endregion
  52. // #region 辅助方法
  53. // /// <summary>
  54. // /// 对象序列化成字符串
  55. // /// </summary>
  56. // /// <typeparam name="T">泛型对象</typeparam>
  57. // /// <param name="value"></param>
  58. // /// <returns></returns>
  59. // private static string ConvertJson<T>(T value)
  60. // {
  61. // string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value);
  62. // return result;
  63. // }
  64. // /// <summary>
  65. // /// RedisValue序列化成对象
  66. // /// </summary>
  67. // /// <typeparam name="T">序列化后的对象</typeparam>
  68. // /// <param name="value">RedisValue</param>
  69. // /// <returns></returns>
  70. // private static T ConvertObj<T>(RedisValue value)
  71. // {
  72. // if (value.IsNull)
  73. // {
  74. // return default(T);
  75. // }
  76. // else
  77. // {
  78. // return JsonConvert.DeserializeObject<T>(value);
  79. // }
  80. // }
  81. // /// <summary>
  82. // /// 多个值序列化成list集合
  83. // /// </summary>
  84. // /// <typeparam name="T">集合对象</typeparam>
  85. // /// <param name="values">RedisValue</param>
  86. // /// <returns></returns>
  87. // private static List<T> ConvetList<T>(RedisValue[] values)
  88. // {
  89. // List<T> result = new List<T>();
  90. // foreach (var item in values)
  91. // {
  92. // var model = ConvertObj<T>(item);
  93. // if (model != null)
  94. // result.Add(model);
  95. // }
  96. // return result;
  97. // }
  98. // private static RedisKey[] ConvertRedisKeys(List<string> redisKeys, string prefix)
  99. // {
  100. // if (string.IsNullOrEmpty(prefix))
  101. // {
  102. // return redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray();
  103. // }
  104. // else
  105. // {
  106. // return redisKeys.Select(redisKey => (RedisKey)(prefix + ":" + redisKey)).ToArray();
  107. // }
  108. // }
  109. // /// <summary>
  110. // /// 获取要操作的库
  111. // /// </summary>
  112. // /// <param name="db">库,0和-1都是第一个库,1是第二个库...</param>
  113. // /// <returns></returns>
  114. // private static int GetOperationDB(RedisEnum db)
  115. // {
  116. // if (db == RedisEnum.DB0)
  117. // {
  118. // return _strDb;
  119. // }
  120. // else
  121. // {
  122. // return (int)db;
  123. // }
  124. // }
  125. // /// <summary>
  126. // /// 获得枚举的Description
  127. // /// </summary>
  128. // /// <param name="value">枚举值</param>
  129. // /// <param name="nameInstead">当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param>
  130. // /// <returns>枚举的Description</returns>
  131. // private static string GetDescription(this Enum value, Boolean nameInstead = true)
  132. // {
  133. // Type type = value.GetType();
  134. // string name = Enum.GetName(type, value);
  135. // if (name == null)
  136. // {
  137. // return null;
  138. // }
  139. // FieldInfo field = type.GetField(name);
  140. // DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
  141. // if (attribute == null && nameInstead == true)
  142. // {
  143. // return name;
  144. // }
  145. // return attribute == null ? null : attribute.Description;
  146. // }
  147. // #endregion
  148. // /// <summary>
  149. // /// 是否存在
  150. // /// </summary>
  151. // /// <param name="key">键</param>
  152. // /// <param name="folder">目录,默认根目录</param>
  153. // /// <param name="db">库,默认读取配置文件</param>
  154. // public static bool KeyExists(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  155. // {
  156. // try
  157. // {
  158. // string strFd = GetDescription(folder);
  159. // return Manager.GetDatabase(GetOperationDB(db)).KeyExists(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key);
  160. // }
  161. // catch (Exception)
  162. // {
  163. // return false;
  164. // }
  165. // }
  166. // /// <summary>
  167. // /// 设置过期时间
  168. // /// </summary>
  169. // /// <param name="key">键</param>
  170. // /// <param name="min">过期时间,单位:分钟</param>
  171. // /// <param name="folder">目录,默认根目录</param>
  172. // /// <param name="db">库,默认读取配置文件</param>
  173. // public static bool KeyExpire(string key, int min = 600, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  174. // {
  175. // try
  176. // {
  177. // string strFd = GetDescription(folder);
  178. // return Manager.GetDatabase(GetOperationDB(db)).KeyExpire(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key, DateTime.Now.AddMinutes(min));
  179. // }
  180. // catch (Exception)
  181. // {
  182. // return false;
  183. // }
  184. // }
  185. // /// <summary>
  186. // /// 修改键
  187. // /// </summary>
  188. // /// <param name="key">键</param>
  189. // /// <param name="newKey">新键</param>
  190. // /// <param name="folder">目录,默认根目录</param>
  191. // /// <param name="db">库,默认读取配置文件</param>
  192. // /// <returns></returns>
  193. // public static bool KeyRename(string key, string newKey, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  194. // {
  195. // try
  196. // {
  197. // string strFd = GetDescription(folder);
  198. // return Manager.GetDatabase(GetOperationDB(db)).KeyRename(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key, string.IsNullOrEmpty(strFd) ? newKey : strFd + ":" + newKey);
  199. // }
  200. // catch (Exception)
  201. // {
  202. // return false;
  203. // }
  204. // }
  205. // /// <summary>
  206. // /// 清空
  207. // /// </summary>
  208. // /// <param name="key">键</param>
  209. // /// <param name="folder">目录,默认根目录</param>
  210. // /// <param name="db">库,默认读取配置文件</param>
  211. // /// <returns></returns>
  212. // public static IEnumerable<RedisKey> AllClear(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  213. // {
  214. // return Manager.GetServer(_strConn, _strPwd).Keys(GetOperationDB(db), key);
  215. // }
  216. // /// <summary>
  217. // /// 删除
  218. // /// </summary>
  219. // /// <param name="key">键</param>
  220. // /// <param name="folder">目录,默认根目录</param>
  221. // /// <param name="db">库,默认读取配置文件</param>
  222. // /// <returns></returns>
  223. // public static bool KeyDelete(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  224. // {
  225. // try
  226. // {
  227. // string strFd = GetDescription(folder);
  228. // return Manager.GetDatabase(GetOperationDB(db)).KeyDelete(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key);
  229. // }
  230. // catch (Exception)
  231. // {
  232. // return false;
  233. // }
  234. // }
  235. // /// <summary>
  236. // /// 批量删除
  237. // /// </summary>
  238. // /// <param name="keys">键</param>
  239. // /// <param name="folder">目录,默认根目录</param>
  240. // /// <param name="db">库,默认读取配置文件</param>
  241. // /// <returns></returns>
  242. // public static long KeyDelete(List<string> keys, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  243. // {
  244. // try
  245. // {
  246. // string strFd = GetDescription(folder);
  247. // return Manager.GetDatabase(GetOperationDB(db)).KeyDelete(ConvertRedisKeys(keys, strFd));
  248. // }
  249. // catch (Exception)
  250. // {
  251. // return 0;
  252. // }
  253. // }
  254. // /// <summary>
  255. // /// 缓存单个字符串
  256. // /// </summary>
  257. // /// <param name="key">键</param>
  258. // /// <param name="value">值</param>
  259. // /// <param name="expireMinutes">过期时间,单位:分钟</param>
  260. // /// <param name="folder">目录,默认根目录</param>
  261. // /// <param name="db">库,默认读取配置文件</param>
  262. // /// <returns></returns>
  263. // public static bool StringSet(string key, string value, int expireMinutes = 600, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  264. // {
  265. // string strFd = GetDescription(folder);
  266. // return Manager.GetDatabase(GetOperationDB(db)).StringSet(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key, value, TimeSpan.FromMinutes(expireMinutes));
  267. // }
  268. // /// <summary>
  269. // /// 批量缓存字符串
  270. // /// </summary>
  271. // /// <param name="keysStr">键</param>
  272. // /// <param name="valuesStr">值</param>
  273. // /// <param name="folder">目录,默认根目录</param>
  274. // /// <param name="db">库,默认读取配置文件</param>
  275. // /// <returns></returns>
  276. // public static bool StringSet(string[] keysStr, string[] valuesStr, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  277. // {
  278. // string strFd = GetDescription(folder);
  279. // var vCount = keysStr.Length;
  280. // var vKeyValuePair = new KeyValuePair<RedisKey, RedisValue>[vCount];
  281. // for (int i = 0; i < vCount; i++)
  282. // {
  283. // vKeyValuePair[i] = new KeyValuePair<RedisKey, RedisValue>(string.IsNullOrEmpty(strFd) ? keysStr[i] : strFd + ":" + keysStr[i], valuesStr[i]);
  284. // }
  285. // return Manager.GetDatabase(GetOperationDB(db)).StringSet(vKeyValuePair);
  286. // }
  287. // /// <summary>
  288. // /// 缓存限时对象
  289. // /// </summary>
  290. // /// <typeparam name="T">类型</typeparam>
  291. // /// <param name="key">键</param>
  292. // /// <param name="obj">值</param>
  293. // /// <param name="expireMinutes">过期时间,单位:分钟</param>
  294. // /// <param name="folder">目录,默认根目录</param>
  295. // /// <param name="db">库,默认读取配置文件</param>
  296. // /// <returns></returns>
  297. // public static bool StringSet<T>(string key, T obj, int expireMinutes = 600, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  298. // {
  299. // string strFd = GetDescription(folder);
  300. // return Manager.GetDatabase(GetOperationDB(db)).StringSet(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key, JsonConvert.SerializeObject(obj), TimeSpan.FromMinutes(expireMinutes));
  301. // }
  302. // /// <summary>
  303. // /// 缓存对象
  304. // /// </summary>
  305. // /// <typeparam name="T">类型</typeparam>
  306. // /// <param name="key">键</param>
  307. // /// <param name="obj">值</param>
  308. // /// <param name="folder">目录,默认根目录</param>
  309. // /// <param name="db">库,默认读取配置文件</param>
  310. // /// <returns></returns>
  311. // public static bool StringSet<T>(string key, T obj, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  312. // {
  313. // string strFd = GetDescription(folder);
  314. // return Manager.GetDatabase(GetOperationDB(db)).StringSet(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key, JsonConvert.SerializeObject(obj));
  315. // }
  316. // /// <summary>
  317. // /// 根据key获取值
  318. // /// </summary>
  319. // /// <param name="key">键</param>
  320. // /// <param name="folder">目录,默认根目录</param>
  321. // /// <param name="db">库,默认读取配置文件</param>
  322. // /// <returns></returns>
  323. // public static string StringGet(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  324. // {
  325. // string strFd = GetDescription(folder);
  326. // return Manager.GetDatabase(GetOperationDB(db)).StringGet(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key);
  327. // }
  328. // /// <summary>
  329. // /// 批量根据key获取
  330. // /// </summary>
  331. // /// <param name="keys">键</param>
  332. // /// <param name="folder">目录,默认根目录</param>
  333. // /// <param name="db">库,默认读取配置文件</param>
  334. // /// <returns></returns>
  335. // public static RedisValue[] StringGet(List<string> keys, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  336. // {
  337. // string strFd = GetDescription(folder);
  338. // return Manager.GetDatabase(GetOperationDB(db)).StringGet(ConvertRedisKeys(keys, strFd));
  339. // }
  340. // /// <summary>
  341. // /// 根据key获取单个对象
  342. // /// </summary>
  343. // /// <typeparam name="T">类型</typeparam>
  344. // /// <param name="key">键</param>
  345. // /// <param name="folder">目录,默认根目录</param>
  346. // /// <param name="db">库,默认读取配置文件</param>
  347. // /// <returns></returns>
  348. // public static T StringGet<T>(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  349. // {
  350. // string strFd = GetDescription(folder);
  351. // string vValue = Manager.GetDatabase(GetOperationDB(db)).StringGet(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key);
  352. // return ConvertObj<T>(vValue);
  353. // }
  354. // /// <summary>
  355. // /// 入栈(后插入的在List前面)
  356. // /// </summary>
  357. // /// <typeparam name="T">类型</typeparam>
  358. // /// <param name="key">键</param>
  359. // /// <param name="value">值</param>
  360. // /// <param name="folder">目录,默认根目录</param>
  361. // /// <param name="db">库,默认读取配置文件</param>
  362. // public static long ListLeftPush<T>(string key, T value, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  363. // {
  364. // string strFd = GetDescription(folder);
  365. // return Manager.GetDatabase(GetOperationDB(db)).ListLeftPush(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key, ConvertJson(value));
  366. // }
  367. // /// <summary>
  368. // /// 批量入栈(后插入的在List前面)
  369. // /// </summary>
  370. // /// <typeparam name="T">类型</typeparam>
  371. // /// <param name="key">键</param>
  372. // /// <param name="values">值</param>
  373. // /// <param name="folder">目录,默认根目录</param>
  374. // /// <param name="db">库,默认读取配置文件</param>
  375. // /// <returns></returns>
  376. // public static long ListLeftPush<T>(string key, List<T> values, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  377. // {
  378. // string strFd = GetDescription(folder);
  379. // var vRedisValues = values.Select(m => (RedisValue)ConvertJson(m)).ToArray();
  380. // return Manager.GetDatabase(GetOperationDB(db)).ListLeftPush(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key, vRedisValues);
  381. // }
  382. // /// <summary>
  383. // /// 出栈(删除最前面的一个元素并返回)
  384. // /// </summary>
  385. // /// <typeparam name="T">类型</typeparam>
  386. // /// <param name="key">键</param>
  387. // /// <param name="folder">目录,默认根目录</param>
  388. // /// <param name="db">库,默认读取配置文件</param>
  389. // /// <returns></returns>
  390. // public static T ListLeftPop<T>(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  391. // {
  392. // string strFd = GetDescription(folder);
  393. // var vRedisValues = Manager.GetDatabase(GetOperationDB(db)).ListLeftPop(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key);
  394. // return ConvertObj<T>(vRedisValues);
  395. // }
  396. // /// <summary>
  397. // /// 入队(后插入的在List后面)
  398. // /// </summary>
  399. // /// <typeparam name="T">类型</typeparam>
  400. // /// <param name="key">键</param>
  401. // /// <param name="value">值</param>
  402. // /// <param name="folder">目录,默认根目录</param>
  403. // /// <param name="db">库,默认读取配置文件</param>
  404. // public static long ListRightPush<T>(string key, T value, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  405. // {
  406. // string strFd = GetDescription(folder);
  407. // return Manager.GetDatabase(GetOperationDB(db)).ListRightPush(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key, ConvertJson(value));
  408. // }
  409. // /// <summary>
  410. // /// 批量入队(后插入的在List后面)
  411. // /// </summary>
  412. // /// <typeparam name="T">类型</typeparam>
  413. // /// <param name="key">键</param>
  414. // /// <param name="values">值</param>
  415. // /// <param name="folder">目录,默认根目录</param>
  416. // /// <param name="db">库,默认读取配置文件</param>
  417. // /// <returns></returns>
  418. // public static long ListRightPush<T>(string key, List<T> values, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  419. // {
  420. // string strFd = GetDescription(folder);
  421. // var vRedisValues = values.Select(m => (RedisValue)ConvertJson(m)).ToArray();
  422. // return Manager.GetDatabase(GetOperationDB(db)).ListRightPush(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key, vRedisValues);
  423. // }
  424. // /// <summary>
  425. // /// 获取
  426. // /// <typeparam name="T">类型</typeparam>
  427. // /// <param name="key">键</param>
  428. // /// <param name="start">索引开始</param>
  429. // /// <param name="stop">索引结束</param>
  430. // /// <param name="folder">目录,默认根目录</param>
  431. // /// <param name="db">库,默认读取配置文件</param>
  432. // /// <returns></returns>
  433. // public static List<T> ListRange<T>(string key, long start = 0, long stop = -1, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  434. // {
  435. // string strFd = GetDescription(folder);
  436. // var vRedisValues = Manager.GetDatabase(GetOperationDB(db)).ListRange(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key, start, stop);
  437. // return ConvetList<T>(vRedisValues);
  438. // }
  439. // /// <summary>
  440. // /// 获取个数
  441. // /// </summary>
  442. // /// <param name="key">键</param>
  443. // /// <param name="folder">目录,默认根目录</param>
  444. // /// <param name="db">库,默认读取配置文件</param>
  445. // /// <returns></returns>
  446. // public static long ListLength(string key, RedisFolderEnum folder = RedisFolderEnum.Root, RedisEnum db = RedisEnum.DB0)
  447. // {
  448. // string strFd = GetDescription(folder);
  449. // return Manager.GetDatabase(GetOperationDB(db)).ListLength(string.IsNullOrEmpty(strFd) ? key : strFd + ":" + key);
  450. // }
  451. //}
  452. #endregion
  453. #region MyRegion
  454. /// <summary>
  455. /// Redis帮助类
  456. /// </summary>
  457. //public class RedisHelper : IDisposable
  458. //{
  459. // private static readonly object Locker = new object();
  460. // private static ConnectionMultiplexer redis = null;
  461. // private static bool connected = false;
  462. // private IDatabase db = null;
  463. // private static string _ip;
  464. // private static string _port;
  465. // private static string _pwd;
  466. // public bool IsConnected { get { GetRedisConnect(); return redis.IsConnected; } }
  467. // //public RedisHelper(string ip, string port, string pwd = "")
  468. // //{
  469. // // _ip = ip;
  470. // // _port = port;
  471. // // _pwd = pwd;
  472. // //}
  473. // /// <summary>
  474. // /// Redis连接
  475. // /// </summary>
  476. // /// <returns></returns>
  477. // private int GetRedisConnect()
  478. // {
  479. // if (connected)
  480. // {
  481. // return 0;
  482. // }
  483. // lock (Locker)
  484. // {
  485. // if (redis == null || !redis.IsConnected)
  486. // {
  487. // redis = ConnectionMultiplexer.Connect($"{_ip}:{_port},password={_pwd},abortConnect = false");
  488. // }
  489. // }
  490. // connected = true;
  491. // return 0;
  492. // }
  493. // public void Using(Action<RedisHelper> action)
  494. // {
  495. // using (var redisHelper = new RedisHelper(_ip, _port, _pwd))
  496. // {
  497. // action(redisHelper);
  498. // }
  499. // }
  500. // public RedisHelper Use(int redisEnum)
  501. // {
  502. // db = redis.GetDatabase(redisEnum);
  503. // //Log.Logs($"RedisDB Conntet State: {redis.IsConnected}");
  504. // var t = db.Ping();
  505. // //Log.Logs($"RedisDB Select {i}, Ping.{t.TotalMilliseconds}ms");
  506. // return this;
  507. // }
  508. // public void Close(bool allowCommandsToComplete = true)
  509. // {
  510. // if (redis != null)
  511. // {
  512. // redis.Close(allowCommandsToComplete);
  513. // }
  514. // }
  515. // public void CloseAsync(bool allowCommandsToComplete = true)
  516. // {
  517. // if (redis != null)
  518. // {
  519. // redis.CloseAsync(allowCommandsToComplete);
  520. // }
  521. // }
  522. // public void Dispose()
  523. // {
  524. // db = null;
  525. // }
  526. // #region 发布订阅
  527. // public delegate void RedisDeletegate(string str);
  528. // public event RedisDeletegate RedisSubMessageEvent;
  529. // /// <summary>
  530. // /// 发布消息
  531. // /// </summary>
  532. // /// <param name="channel"></param>
  533. // /// <param name="msg"></param>
  534. // /// <returns></returns>
  535. // public long RedisPublish(string channel, string msg)
  536. // {
  537. // ISubscriber sub = redis.GetSubscriber();
  538. // return sub.Publish(channel, msg);
  539. // }
  540. // /// <summary>
  541. // /// 订阅消息
  542. // /// </summary>
  543. // /// <param name="subChannael"></param>
  544. // /// <param name=""></param>
  545. // public void RedisSubScribe(string subChannael)
  546. // {
  547. // ISubscriber sub = redis.GetSubscriber();
  548. // sub.Subscribe(subChannael, (channel, message) =>
  549. // {
  550. // RedisSubMessageEvent?.Invoke(message); //触发事件
  551. // });
  552. // }
  553. // /// <summary>
  554. // /// 取消订阅
  555. // /// </summary>
  556. // /// <param name="channel"></param>
  557. // public void Unsubscribe(string channel)
  558. // {
  559. // ISubscriber sub = redis.GetSubscriber();
  560. // sub.Unsubscribe(channel);
  561. // }
  562. // /// <summary>
  563. // /// 取消全部订阅
  564. // /// </summary>
  565. // public void UnsubscribeAll()
  566. // {
  567. // ISubscriber sub = redis.GetSubscriber();
  568. // sub.UnsubscribeAll();
  569. // }
  570. // #endregion
  571. // #region String类型操作
  572. // /// <summary>
  573. // /// 设置指定key 的值(默认第0个库)
  574. // /// </summary>
  575. // /// <param name="strKey">指定key的值</param>
  576. // /// <param name="strValue"></param>
  577. // /// <returns></returns>
  578. // public bool InsertStr(string strKey, string strValue)
  579. // {
  580. // var db = redis.GetDatabase();
  581. // return db.StringSet(strKey, strValue);
  582. // }
  583. // /// <summary>
  584. // /// 设置指定key 的值(指定库)
  585. // /// </summary>
  586. // /// <param name="strKey"></param>
  587. // /// <param name="strValue"></param>
  588. // /// <param name="database"></param>
  589. // /// <returns></returns>
  590. // public bool InsertStr(string strKey, string strValue, int database)
  591. // {
  592. // var db = redis.GetDatabase(database);
  593. // return db.StringSet(strKey, strValue);
  594. // }
  595. // /// <summary>
  596. // /// 设置指定key 的值(指定第一个库,指定过期时间)
  597. // /// </summary>
  598. // /// <param name="strKey">指定key的值</param>
  599. // /// <param name="strValue"></param>
  600. // /// <param name="expire"></param>
  601. // public bool InsertStrExpire(string strKey, string strValue, DateTime expire)
  602. // {
  603. // var db = redis.GetDatabase(1);
  604. // db.StringSet(strKey, strValue);
  605. // return db.KeyExpire(strKey, expire);
  606. // }
  607. // /// <summary>
  608. // /// 设置指定key 的值(指定第一个库,指定过期分钟数)
  609. // /// </summary>
  610. // /// <param name="strKey">指定key的值</param>
  611. // /// <param name="strValue"></param>
  612. // /// <param name="timespanmin"></param>
  613. // public bool InsertStrExpire(string strKey, string strValue, int timespanmin)
  614. // {
  615. // var db = redis.GetDatabase(1);
  616. // return db.StringSet(strKey, strValue, TimeSpan.FromMinutes(timespanmin));
  617. // }
  618. // /// <summary>
  619. // /// 设置指定key 的值(指定第一个库,指定过期分钟数)
  620. // /// </summary>
  621. // /// <param name="strKey">指定key的值</param>
  622. // /// <param name="strValue"></param>
  623. // /// <param name="timespanmin"></param>
  624. // public void InsertStrExpireByDatabaseOne(string strKey, string strValue, int timespanmin)
  625. // {
  626. // var db = redis.GetDatabase(1);
  627. // db.StringSet(strKey, strValue, TimeSpan.FromMinutes(timespanmin));
  628. // }
  629. // /// <summary>
  630. // /// 获取指定 key 的值(默认第0个库)
  631. // /// </summary>
  632. // /// <param name="strKey">指定key的值</param>
  633. // /// <returns></returns>
  634. // public string ReadStr(string strKey)
  635. // {
  636. // var db = redis.GetDatabase();
  637. // return db.StringGet(strKey);
  638. // }
  639. // /// <summary>
  640. // /// 获取指定 key 的值(指定第一个库)
  641. // /// </summary>
  642. // /// <param name="strKey">指定key的值</param>
  643. // /// <returns></returns>
  644. // public string ReadStrByDatabaseOne(string strKey)
  645. // {
  646. // var db = redis.GetDatabase(1);
  647. // return db.StringGet(strKey);
  648. // }
  649. // /// <summary>
  650. // /// 获取指定 key 的值(指定第一个库)
  651. // /// </summary>
  652. // /// <param name="strKey">指定key的值</param>
  653. // /// <param name="database"></param>
  654. // /// <returns></returns>
  655. // public string ReadStrByDatabase(string strKey, int database)
  656. // {
  657. // var db = redis.GetDatabase(database);
  658. // return db.StringGet(strKey);
  659. // }
  660. // /// <summary>
  661. // /// 删除指定key的值(默认第0个库)
  662. // /// </summary>
  663. // /// <param name="strKey">指定key的值</param>
  664. // public bool DeleteStr(string strKey)
  665. // {
  666. // var db = redis.GetDatabase();
  667. // return db.KeyDelete(strKey);
  668. // }
  669. // /// <summary>
  670. // /// 删除指定key的值(默认第0个库)
  671. // /// </summary>
  672. // /// <param name="strKey">指定key的值</param>
  673. // /// <param name="database">指定库的值</param>
  674. // public bool DeleteStrByDatabase(string strKey, int database)
  675. // {
  676. // var db = redis.GetDatabase(database);
  677. // return db.KeyDelete(strKey);
  678. // }
  679. // public bool Exist(string strKey)
  680. // {
  681. // var db = redis.GetDatabase();
  682. // return db.KeyExists(strKey);
  683. // }
  684. // #endregion
  685. // #region Hash类型操作
  686. // public bool InsertHash(string tablename, string strKey, string strValue)
  687. // {
  688. // var db = redis.GetDatabase();
  689. // return db.HashSet(tablename, strKey, strValue);
  690. // }
  691. // public string ReadHash(string tablename, string strKey)
  692. // {
  693. // var db = redis.GetDatabase();
  694. // return db.HashGet(tablename, strKey);
  695. // }
  696. // public bool ExistHash(string tablename, string strKey)
  697. // {
  698. // var db = redis.GetDatabase();
  699. // return db.HashExists(tablename, strKey);
  700. // }
  701. // public bool DeleteHash(string tablename, string strKey)
  702. // {
  703. // var db = redis.GetDatabase();
  704. // return db.HashDelete(tablename, strKey);
  705. // }
  706. // #endregion
  707. //}
  708. #endregion
  709. public class RedisHelper : IDisposable
  710. {
  711. //连接字符串
  712. private string _connectionString;
  713. //实例名称
  714. private string _instanceName;
  715. //默认数据库
  716. private int _defaultDB;
  717. private ConcurrentDictionary<string, ConnectionMultiplexer> _connections;
  718. public RedisHelper(string connectionString, string instanceName, int defaultDB = 0)
  719. {
  720. _connectionString = connectionString;
  721. _instanceName = instanceName;
  722. _defaultDB = defaultDB;
  723. _connections = new ConcurrentDictionary<string, ConnectionMultiplexer>();
  724. }
  725. /// <summary>
  726. /// 获取ConnectionMultiplexer
  727. /// </summary>
  728. /// <returns></returns>
  729. private ConnectionMultiplexer GetConnect()
  730. {
  731. return _connections.GetOrAdd(_instanceName, p => ConnectionMultiplexer.Connect(_connectionString));
  732. }
  733. /// <summary>
  734. /// 获取数据库
  735. /// </summary>
  736. /// <param name="configName"></param>
  737. /// <param name="db">默认为0:优先代码的db配置,其次config中的配置</param>
  738. /// <returns></returns>
  739. public IDatabase GetDatabase(RedisEnum redisEnum)
  740. {
  741. return GetConnect().GetDatabase((int)redisEnum);
  742. }
  743. public IServer GetServer(string configName = null, int endPointsIndex = 0)
  744. {
  745. var confOption = ConfigurationOptions.Parse(_connectionString);
  746. return GetConnect().GetServer(confOption.EndPoints[endPointsIndex]);
  747. }
  748. public ISubscriber GetSubscriber(string configName = null)
  749. {
  750. return GetConnect().GetSubscriber();
  751. }
  752. public void Dispose()
  753. {
  754. if (_connections != null && _connections.Count > 0)
  755. {
  756. foreach (var item in _connections.Values)
  757. {
  758. item.Close();
  759. }
  760. }
  761. }
  762. }
  763. }