RedisHelper.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. using ERP.Framework.Config;
  2. using StackExchange.Redis;
  3. using System.Diagnostics.CodeAnalysis;
  4. namespace ERP.Framework.Cache
  5. {
  6. public static class RedisHelper
  7. {
  8. [NotNull]
  9. private static IDatabase? DB { get; set; }
  10. private static IConnectionMultiplexer? _connMultiplexer;
  11. private static readonly object _lock = new object();
  12. public static void Init(RedisConfig redisConfig)
  13. {
  14. try
  15. {
  16. var redisConnectionStr = $"{redisConfig.Host}:{redisConfig.Port}";
  17. var options = ConfigurationOptions.Parse(redisConnectionStr);
  18. options.Password = redisConfig.Password;
  19. var connectionMultiplexer = GetConnectRedisMultiplexer(options);
  20. DB = connectionMultiplexer.GetDatabase();
  21. }
  22. catch (Exception err)
  23. {
  24. // Todo Redis初始化异常
  25. }
  26. }
  27. private static IConnectionMultiplexer GetConnectRedisMultiplexer(ConfigurationOptions options)
  28. {
  29. if (_connMultiplexer == null)
  30. {
  31. lock (_lock)
  32. {
  33. if (_connMultiplexer != null)
  34. {
  35. return _connMultiplexer;
  36. }
  37. _connMultiplexer = ConnectionMultiplexer.Connect(options);
  38. //Todo 注册事件
  39. //_connMultiplexer.ConnectionFailed
  40. //_connMultiplexer.ConnectionFailed += MuxerConnectionFailed;
  41. //_connMultiplexer.ConnectionRestored += MuxerConnectionRestored;
  42. //_connMultiplexer.ErrorMessage += MuxerErrorMessage;
  43. //_connMultiplexer.ConfigurationChanged += MuxerConfigurationChanged;
  44. //_connMultiplexer.HashSlotMoved += MuxerHashSlotMoved;
  45. //_connMultiplexer.InternalError += MuxerInternalError;
  46. }
  47. }
  48. return _connMultiplexer;
  49. }
  50. #region Event
  51. /// <summary>
  52. /// 添加注册事件
  53. /// </summary>
  54. private static void AddRegisterEvent()
  55. {
  56. //_connMultiplexer.ConnectionRestored += ConnMultiplexer_ConnectionRestored;
  57. //_connMultiplexer.ConnectionFailed += ConnMultiplexer_ConnectionFailed;
  58. //_connMultiplexer.ErrorMessage += ConnMultiplexer_ErrorMessage;
  59. //_connMultiplexer.ConfigurationChanged += ConnMultiplexer_ConfigurationChanged;
  60. //_connMultiplexer.HashSlotMoved += ConnMultiplexer_HashSlotMoved;
  61. //_connMultiplexer.InternalError += ConnMultiplexer_InternalError;
  62. //_connMultiplexer.ConfigurationChangedBroadcast += ConnMultiplexer_ConfigurationChangedBroadcast;
  63. }
  64. ///// <summary>
  65. ///// 重新配置广播时(通常意味着主从同步更改)
  66. ///// </summary>
  67. ///// <param name="sender"></param>
  68. ///// <param name="e"></param>
  69. //private static void ConnMultiplexer_ConfigurationChangedBroadcast(object sender, EndPointEventArgs e)
  70. //{
  71. //}
  72. ///// <summary>
  73. ///// 发生内部错误时(主要用于调试)
  74. ///// </summary>
  75. ///// <param name="sender"></param>
  76. ///// <param name="e"></param>
  77. //private static void ConnMultiplexer_InternalError(object sender, InternalErrorEventArgs e)
  78. //{
  79. //}
  80. ///// <summary>
  81. ///// 更改集群时
  82. ///// </summary>
  83. ///// <param name="sender"></param>
  84. ///// <param name="e"></param>
  85. //private static void ConnMultiplexer_HashSlotMoved(object sender, HashSlotMovedEventArgs e)
  86. //{
  87. //}
  88. ///// <summary>
  89. ///// 配置更改时
  90. ///// </summary>
  91. ///// <param name="sender"></param>
  92. ///// <param name="e"></param>
  93. //private static void ConnMultiplexer_ConfigurationChanged(object sender, EndPointEventArgs e)
  94. //{
  95. //}
  96. ///// <summary>
  97. ///// 发生错误时
  98. ///// </summary>
  99. ///// <param name="sender"></param>
  100. ///// <param name="e"></param>
  101. //private static void ConnMultiplexer_ErrorMessage(object sender, RedisErrorEventArgs e)
  102. //{
  103. //}
  104. ///// <summary>
  105. ///// 物理连接失败时
  106. ///// </summary>
  107. ///// <param name="sender"></param>
  108. ///// <param name="e"></param>
  109. //private static void ConnMultiplexer_ConnectionFailed(object sender, ConnectionFailedEventArgs e)
  110. //{
  111. //}
  112. ///// <summary>
  113. ///// 建立物理连接时
  114. ///// </summary>
  115. ///// <param name="sender"></param>
  116. ///// <param name="e"></param>
  117. //private static void ConnMultiplexer_ConnectionRestored(object sender, ConnectionFailedEventArgs e)
  118. //{
  119. //}
  120. #endregion Event
  121. #region String
  122. /// <summary>
  123. /// set or update the value for string key
  124. /// </summary>
  125. /// <param name="key"></param>
  126. /// <param name="value"></param>
  127. /// <returns></returns>
  128. public static bool Save(string key, string value)
  129. {
  130. return DB.StringSet(key, value);
  131. }
  132. /// <summary>
  133. /// set or update the value for string key
  134. /// </summary>
  135. /// <param name="key"></param>
  136. /// <param name="value"></param>
  137. /// <returns></returns>
  138. public static bool SaveExpire(string key, string value, TimeSpan? expireMinutes)
  139. {
  140. return DB.StringSet(key, value, expireMinutes);
  141. }
  142. /// <summary>
  143. /// set or update the value for string key
  144. /// </summary>
  145. /// <param name="key"></param>
  146. /// <param name="value"></param>
  147. /// <returns></returns>
  148. public static bool SaveExpire(string key, string value, int expireMinutes)
  149. {
  150. return DB.StringSet(key, value, TimeSpan.FromMinutes(expireMinutes));
  151. }
  152. /// <summary>
  153. /// get the value for string key
  154. /// </summary>
  155. /// <param name="key"></param>
  156. /// <returns></returns>
  157. public static string Get(string key)
  158. {
  159. return DB.StringGet(key);
  160. }
  161. /// <summary>
  162. /// get the value for string key
  163. /// </summary>
  164. /// <param name="key"></param>
  165. /// <returns></returns>
  166. public static RedisValueWithExpiry GetWithExpire(string key)
  167. {
  168. return DB.StringGetWithExpiry(key);
  169. }
  170. /// <summary>
  171. /// Delete the value for string key
  172. /// </summary>
  173. /// <param name="key"></param>
  174. /// <returns></returns>
  175. public static bool Delete(string key)
  176. {
  177. return DB.KeyDelete(key);
  178. }
  179. #endregion String
  180. ///// <summary>
  181. ///// 新增Redis值(有时限)
  182. ///// </summary>
  183. ///// <param name="key">id</param>
  184. ///// <param name="value">值</param>
  185. ///// <param name="expireMinutes">时限(分钟,默认30天)</param>
  186. ///// <returns></returns>
  187. //public static bool AddExpire(string key, string value, int expireMinutes = 24 * 60 * 30)
  188. // => new RedisHelper().AddExpireValue(key, value, expireMinutes);
  189. ///// <summary>
  190. ///// 保存一个对象
  191. ///// </summary>
  192. ///// <typeparam name="T"></typeparam>
  193. ///// <param name="key"></param>
  194. ///// <param name="obj"></param>
  195. ///// <returns></returns>
  196. //public bool SetStringKey<T>(string key, T obj, int expireMinutes = 0)
  197. //{
  198. // string json = JsonConvert.SerializeObject(obj);
  199. // if (expireMinutes > 0)
  200. // {
  201. // return DB.StringSet(key, json, TimeSpan.FromMinutes(expireMinutes));
  202. // }
  203. // else
  204. // return DB.StringSet(key, json);
  205. //}
  206. ///// <summary>
  207. ///// 获取一个key的对象
  208. ///// </summary>
  209. ///// <typeparam name="T"></typeparam>
  210. ///// <param name="key"></param>
  211. ///// <returns></returns>
  212. //public T GetStringKey<T>(string key) where T : class
  213. //{
  214. // var result = DB.StringGet(key);
  215. // if (string.IsNullOrEmpty(result))
  216. // {
  217. // return null;
  218. // }
  219. // try
  220. // {
  221. // return JsonConvert.DeserializeObject<T>(result);
  222. // }
  223. // catch
  224. // {
  225. // return null;
  226. // }
  227. //}
  228. ///// <summary>
  229. ///// set or update the HashValue for string key
  230. ///// </summary>
  231. ///// <param name="key"></param>
  232. ///// <param name="hashkey"></param>
  233. ///// <param name="value"></param>
  234. ///// <returns></returns>
  235. //public bool SetHashValue(string key, string hashkey, string value)
  236. //{
  237. // return DB.HashSet(key, hashkey, value);
  238. //}
  239. ///// <summary>
  240. ///// set or update the HashValue for string key
  241. ///// </summary>
  242. ///// <typeparam name="T"></typeparam>
  243. ///// <param name="key"></param>
  244. ///// <param name="hashkey"></param>
  245. ///// <param name="t">defined class</param>
  246. ///// <returns></returns>
  247. //public bool SetHashValue<T>(String key, string hashkey, T t) where T : class
  248. //{
  249. // var json = JsonConvert.SerializeObject(t);
  250. // return DB.HashSet(key, hashkey, json);
  251. //}
  252. //public static void HashSet<T>(string key, List<T> list, Func<T, string> getModelId)
  253. // => new RedisHelper().HashSetValue(key, list, getModelId);
  254. //public static void HashSetExpire<T>(string key, List<T> list, Func<T, string> getModelId, int expireTime = 24 * 60 * 30)
  255. //=> new RedisHelper().HashSetExpireValue(key, list, getModelId, expireTime);
  256. ///// <summary>
  257. ///// 保存一个集合
  258. ///// </summary>
  259. ///// <typeparam name="T"></typeparam>
  260. ///// <param name="key">Redis Key</param>
  261. ///// <param name="list">数据集合</param>
  262. ///// <param name="getModelId"></param>
  263. //public void HashSetValue<T>(string key, List<T> list, Func<T, string> getModelId)
  264. //{
  265. // List<HashEntry> listHashEntry = new List<HashEntry>();
  266. // foreach (var item in list)
  267. // {
  268. // string json = JsonConvert.SerializeObject(item);
  269. // listHashEntry.Add(new HashEntry(getModelId(item), json));
  270. // }
  271. // DB.HashSet(key, listHashEntry.ToArray());
  272. //}
  273. ///// <summary>
  274. ///// 保存一个集合
  275. ///// </summary>
  276. ///// <typeparam name="T"></typeparam>
  277. ///// <param name="key">Redis Key</param>
  278. ///// <param name="list">数据集合</param>
  279. ///// <param name="getModelId"></param>
  280. //private void HashSetExpireValue<T>(string key, List<T> list, Func<T, string> getModelId, int expireTime)
  281. //{
  282. // List<HashEntry> listHashEntry = new List<HashEntry>();
  283. // foreach (var item in list)
  284. // {
  285. // string json = JsonConvert.SerializeObject(item);
  286. // listHashEntry.Add(new HashEntry(getModelId(item), json));
  287. // }
  288. // DB.HashSet(key, listHashEntry.ToArray());
  289. // DB.KeyExpire(key, TimeSpan.FromMinutes(expireTime));
  290. //}
  291. ///// <summary>
  292. ///// 获取hashkey所有的值
  293. ///// </summary>
  294. ///// <typeparam name="T"></typeparam>
  295. ///// <param name="key"></param>
  296. ///// <returns></returns>
  297. //public List<T> HashGetAll<T>(string key) where T : class
  298. //{
  299. // List<T> result = new List<T>();
  300. // HashEntry[] arr = DB.HashGetAll(key);
  301. // foreach (var item in arr)
  302. // {
  303. // if (!item.Value.IsNullOrEmpty)
  304. // {
  305. // result.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<T>(item.Value));
  306. // }
  307. // }
  308. // return result;
  309. //}
  310. ///// <summary>
  311. ///// get the HashValue for string key and hashkey
  312. ///// </summary>
  313. ///// <param name="key">Represents a key that can be stored in redis</param>
  314. ///// <param name="hashkey"></param>
  315. ///// <returns></returns>
  316. //public RedisValue GetHashValue(string key, string hashkey)
  317. //{
  318. // RedisValue result = DB.HashGet(key, hashkey);
  319. // return result;
  320. //}
  321. ///// <summary>
  322. ///// get the HashValue for string key and hashkey
  323. ///// </summary>
  324. ///// <param name="key">Represents a key that can be stored in redis</param>
  325. ///// <param name="hashkey"></param>
  326. ///// <returns></returns>
  327. //public T GetHashValue<T>(string key, string hashkey) where T : class
  328. //{
  329. // RedisValue result = DB.HashGet(key, hashkey);
  330. // if (string.IsNullOrEmpty(result))
  331. // {
  332. // return null;
  333. // }
  334. // T t = JsonConvert.DeserializeObject<T>(result);
  335. // return null;
  336. //}
  337. ///// <summary>
  338. ///// delete the HashValue for string key and hashkey
  339. ///// </summary>
  340. ///// <param name="key"></param>
  341. ///// <param name="hashkey"></param>
  342. ///// <returns></returns>
  343. //public bool DeleteHashValue(string key, string hashkey)
  344. //{
  345. // return DB.HashDelete(key, hashkey);
  346. //}
  347. }
  348. }