RedisHelper.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. using Newtonsoft.Json;
  2. using ServiceStack.Redis;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Linq;
  7. using System.Text;
  8. namespace CP.Common.redis
  9. {
  10. public class RedisHelper : IDisposable
  11. {
  12. private static RedisClient redisCli = null;
  13. /// <summary>
  14. /// 建立连接
  15. /// </summary>
  16. /// <param name="redisConfig">redis配置节点</param>
  17. public static void CreateClient(string redisConfig, bool isAuto = false)
  18. {
  19. var json = string.Empty;
  20. if (!isAuto)
  21. json = ConfigurationManager.AppSettings["ReidsConfig"]?.ToString().Trim() ?? "";
  22. else
  23. json = ConfigurationManager.AppSettings[redisConfig]?.ToString().Trim() ?? "";
  24. if (string.IsNullOrEmpty(json))
  25. throw new Exception("初始化redis失败:未找到配置节点");
  26. RedisConfig config = null;
  27. try
  28. {
  29. config = JsonConvert.DeserializeObject<RedisConfig>(json);
  30. }
  31. catch (Exception ex)
  32. {
  33. throw new Exception("初始化redis失败:配置节点json数据格式错误。" + ex.Message);
  34. }
  35. if (redisCli == null)
  36. {
  37. try
  38. {
  39. redisCli = new RedisClient(config.host, config.port, config.password, config.db);
  40. }
  41. catch (Exception ex)
  42. {
  43. throw new Exception("初始化redis失败:" + string.Format("{0}:{1} {2} {3}", config.host, config.port, config.password, config.db) + "\n" + ex.Message);
  44. }
  45. }
  46. }
  47. public static RedisClient CreateClient2(string redisConfig, bool isAuto = false)
  48. {
  49. var json = string.Empty;
  50. if (!isAuto)
  51. json = ConfigurationManager.AppSettings["ReidsConfig"]?.ToString().Trim() ?? "";
  52. else
  53. json = ConfigurationManager.AppSettings[redisConfig]?.ToString().Trim() ?? "";
  54. if (string.IsNullOrEmpty(json))
  55. throw new Exception("初始化redis失败:未找到配置节点");
  56. RedisConfig config = null;
  57. try
  58. {
  59. config = JsonConvert.DeserializeObject<RedisConfig>(json);
  60. }
  61. catch (Exception ex)
  62. {
  63. throw new Exception("初始化redis失败:配置节点json数据格式错误。" + ex.Message);
  64. }
  65. if (redisCli == null)
  66. {
  67. try
  68. {
  69. redisCli = new RedisClient(config.host, config.port);
  70. }
  71. catch (Exception ex)
  72. {
  73. throw new Exception("初始化redis失败:" + string.Format("{0}:{1} {2} {3}", config.host, config.port, config.password, config.db) + "\n" + ex.Message);
  74. }
  75. }
  76. return redisCli;
  77. }
  78. /// <summary>
  79. /// 创建连接池
  80. /// </summary>
  81. /// <param name="readWriteHosts"></param>
  82. /// <param name="readOnlyHosts"></param>
  83. /// <returns></returns>
  84. private static PooledRedisClientManager CreatePool(string[] readWriteHosts, string[] readOnlyHosts, int db)
  85. {
  86. //支持读写分离,均衡负载
  87. return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig
  88. {
  89. DefaultDb = db,
  90. MaxWritePoolSize = 50,//“写”链接池链接数
  91. MaxReadPoolSize = 50,//“读”链接池链接数
  92. AutoStart = true,
  93. });
  94. }
  95. /// <summary>
  96. /// 使用连接池获取链接
  97. /// </summary>
  98. public static void CreateClientByPool(string[] readWriteHosts, string[] readOnlyHosts, int db)
  99. {
  100. redisCli = (RedisClient)CreatePool(readWriteHosts, readOnlyHosts, db).GetClient();
  101. }
  102. #region string
  103. /// <summary>
  104. /// 获取key,返回string格式
  105. /// </summary>
  106. /// <param name="key"></param>
  107. /// <returns></returns>
  108. public static string GetValueString(string key)
  109. {
  110. string value = redisCli.GetValue(key);
  111. return value;
  112. }
  113. public static bool AddValue<T>(string key, T value)
  114. {
  115. return redisCli.Add<T>(key, value);
  116. }
  117. /// <summary>
  118. /// 获取key,返回byte[]格式
  119. /// </summary>
  120. /// <param name="key"></param>
  121. /// <returns></returns>
  122. public static byte[] GetValueByte(string key)
  123. {
  124. byte[] value = redisCli.Get(key);
  125. return value;
  126. }
  127. /// <summary>
  128. /// 删除key
  129. /// </summary>
  130. /// <param name="key"></param>
  131. /// <returns></returns>
  132. public static bool DeleteKey(string key)
  133. {
  134. if (Exists(key))
  135. return redisCli.Remove(key);
  136. return false;
  137. }
  138. public static bool Exists(string key)
  139. {
  140. return redisCli.Exists(key) > 0 ? true : false;
  141. }
  142. #endregion
  143. #region Hash
  144. public static bool SetEntryInHash(string hashId, string key, string value)
  145. {
  146. return redisCli.SetEntryInHash(hashId, key, value);
  147. }
  148. public static bool RemoveEntryFromHash(string hashId, string key)
  149. {
  150. return redisCli.RemoveEntryFromHash(hashId, key);
  151. }
  152. /// <summary>
  153. /// 获得某个hash型key下的所有字段
  154. /// </summary>
  155. /// <param name="hashId"></param>
  156. /// <returns></returns>
  157. public static List<string> GetHashFields(string hashId)
  158. {
  159. List<string> hashFields = redisCli.GetHashKeys(hashId);
  160. return hashFields;
  161. }
  162. /// <summary>
  163. /// 获得某个hash型key下的所有值
  164. /// </summary>
  165. /// <param name="hashId"></param>
  166. /// <returns></returns>
  167. public static List<string> GetHashValues(string hashId)
  168. {
  169. List<string> hashValues = redisCli.GetHashValues(hashId);
  170. return hashValues;
  171. }
  172. /// <summary>
  173. /// 获得hash型key某个字段的值
  174. /// </summary>
  175. /// <param name="key"></param>
  176. /// <param name="field"></param>
  177. /// <returns></returns>
  178. public static string GetHashField(string key, string field)
  179. {
  180. string value = redisCli.GetValueFromHash(key, field);
  181. return value;
  182. }
  183. /// <summary>
  184. /// 设置hash型key某个字段的值
  185. /// </summary>
  186. /// <param name="key"></param>
  187. /// <param name="field"></param>
  188. /// <param name="value"></param>
  189. public static void SetHashField(string key, string field, string value)
  190. {
  191. //return redisCli.SetEntryInHash(key, field, value);
  192. redisCli.SetEntryInHash(key, field, value);
  193. }
  194. /// <summary>
  195. /// 使某个字段增加
  196. /// </summary>
  197. /// <param name="key"></param>
  198. /// <param name="field"></param>
  199. /// <param name="incre"></param>
  200. public static void SetHashIncr(string key, string field, long incre)
  201. {
  202. redisCli.IncrementValueInHash(key, field, incre);
  203. }
  204. #endregion
  205. #region List
  206. /// <summary>
  207. /// 向list类型数据添加成员,向列表底部(右侧)添加
  208. /// </summary>
  209. /// <param name="list"></param>
  210. /// <param name="item"></param>
  211. public static void AddItemToListRight(string list, string item)
  212. {
  213. redisCli.AddItemToList(list, item);
  214. }
  215. /// <summary>
  216. /// 获取list元素个数
  217. /// </summary>
  218. /// <param name="list"></param>
  219. /// <returns></returns>
  220. public static long GetListCount(string list)
  221. {
  222. return redisCli.GetListCount(list);
  223. }
  224. /// <summary>
  225. /// 获取list所有元素
  226. /// </summary>
  227. /// <param name="list"></param>
  228. /// <returns></returns>
  229. public static List<string> GetAllItemsFromList(string list)
  230. {
  231. return redisCli.GetAllItemsFromList(list);
  232. }
  233. /// <summary>
  234. /// 获取list中某个元素的值
  235. /// </summary>
  236. /// <param name="list"></param>
  237. /// <returns></returns>
  238. public static void SetItemInList(string list, int index, string value)
  239. {
  240. redisCli.SetItemInList(list, index, value);
  241. }
  242. /// <summary>
  243. /// 删除list中某个元素
  244. /// </summary>
  245. /// <param name="list"></param>
  246. /// <param name="value"></param>
  247. public static void RemoveItemFromList(string list, int index)
  248. {
  249. var value = redisCli.GetItemFromList(list, index);
  250. if (value != null)
  251. redisCli.RemoveItemFromList(list, value);
  252. }
  253. /// <summary>
  254. /// 向list类型数据添加成员,向列表顶部(左侧)添加
  255. /// </summary>
  256. /// <param name="list"></param>
  257. /// <param name="item"></param>
  258. public static void AddItemToListLeft(string list, string item)
  259. {
  260. redisCli.LPush(list, Encoding.Default.GetBytes(item));
  261. }
  262. /// <summary>
  263. /// 从list类型数据读取所有成员
  264. /// </summary>
  265. /// <param name="list"></param>
  266. /// <returns></returns>
  267. public static List<string> GetListAllItems(string list)
  268. {
  269. List<string> listMembers = redisCli.GetAllItemsFromList(list);
  270. return listMembers;
  271. }
  272. /// <summary>
  273. /// 从list类型数据指定索引处获取数据,支持正索引和负索引
  274. /// </summary>
  275. /// <param name="list"></param>
  276. /// <param name="index"></param>
  277. /// <returns></returns>
  278. public static string GetItemFromList(string list, int index)
  279. {
  280. string item = redisCli.GetItemFromList(list, index);
  281. return item;
  282. }
  283. /// <summary>
  284. /// 向列表底部(右侧)批量添加数据
  285. /// </summary>
  286. /// <param name="list"></param>
  287. /// <param name="values"></param>
  288. public static void GetRangeToList(string list, List<string> values)
  289. {
  290. redisCli.AddRangeToList(list, values);
  291. }
  292. #endregion
  293. #region Set
  294. /// <summary>
  295. /// 向集合中添加数据
  296. /// </summary>
  297. /// <param name="setId"></param>
  298. /// <param name="item"></param>
  299. public static void AddItemToSet(string setId, string item)
  300. {
  301. redisCli.AddItemToSet(setId, item);
  302. }
  303. /// <summary>
  304. /// 从集合中移除数据
  305. /// </summary>
  306. /// <param name="setId"></param>
  307. /// <param name="item"></param>
  308. public static void RemoveItemFromSet(string setId, string item)
  309. {
  310. redisCli.RemoveItemFromSet(setId, item);
  311. }
  312. /// <summary>
  313. /// 获得集合中所有数据
  314. /// </summary>
  315. /// <param name="set"></param>
  316. /// <returns></returns>
  317. public static HashSet<string> GetAllItemsFromSet(string set)
  318. {
  319. HashSet<string> items = redisCli.GetAllItemsFromSet(set);
  320. return items;
  321. }
  322. /// <summary>
  323. /// 获取fromSet集合和其他集合不同的数据
  324. /// </summary>
  325. /// <param name="fromSet"></param>
  326. /// <param name="toSet"></param>
  327. /// <returns></returns>
  328. public static HashSet<string> GetSetDiff(string fromSet, params string[] toSet)
  329. {
  330. HashSet<string> diff = redisCli.GetDifferencesFromSet(fromSet, toSet);
  331. return diff;
  332. }
  333. /// <summary>
  334. /// 获得所有集合的并集
  335. /// </summary>
  336. /// <param name="set"></param>
  337. /// <returns></returns>
  338. public static HashSet<string> GetSetUnion(params string[] set)
  339. {
  340. HashSet<string> union = redisCli.GetUnionFromSets(set);
  341. return union;
  342. }
  343. /// <summary>
  344. /// 获得所有集合的交集
  345. /// </summary>
  346. /// <param name="set"></param>
  347. /// <returns></returns>
  348. public static HashSet<string> GetSetInter(params string[] set)
  349. {
  350. HashSet<string> inter = redisCli.GetIntersectFromSets(set);
  351. return inter;
  352. }
  353. #endregion
  354. #region SortedSet
  355. /// <summary>
  356. /// 向有序集合中添加元素
  357. /// </summary>
  358. /// <param name="set"></param>
  359. /// <param name="value"></param>
  360. /// <param name="score"></param>
  361. public static bool AddItemToSortedSet(string set, string value, long score)
  362. {
  363. return redisCli.AddItemToSortedSet(set, value, score);
  364. }
  365. public static bool AddItemToSortedSet(string set, string value, double score)
  366. {
  367. return redisCli.AddItemToSortedSet(set, value, score);
  368. }
  369. /// <summary>
  370. /// 获得某个值在有序集合中的排名,按分数的降序排列
  371. /// </summary>
  372. /// <param name="set"></param>
  373. /// <param name="value"></param>
  374. /// <returns></returns>
  375. public static long GetItemIndexInSortedSetDesc(string set, string value)
  376. {
  377. long index = redisCli.GetItemIndexInSortedSetDesc(set, value);
  378. return index;
  379. }
  380. /// <summary>
  381. /// 获得某个值在有序集合中的排名,按分数的升序排列
  382. /// </summary>
  383. /// <param name="set"></param>
  384. /// <param name="value"></param>
  385. /// <returns></returns>
  386. public static long GetItemIndexInSortedSet(string set, string value)
  387. {
  388. long index = redisCli.GetItemIndexInSortedSet(set, value);
  389. return index;
  390. }
  391. /// <summary>
  392. /// 获得有序集合中某个值得分数
  393. /// </summary>
  394. /// <param name="set"></param>
  395. /// <param name="value"></param>
  396. /// <returns></returns>
  397. public static double GetItemScoreInSortedSet(string set, string value)
  398. {
  399. double score = redisCli.GetItemScoreInSortedSet(set, value);
  400. return score;
  401. }
  402. /// <summary>
  403. /// 获得有序集合中,某个排名范围的所有值
  404. /// </summary>
  405. /// <param name="set"></param>
  406. /// <param name="beginRank"></param>
  407. /// <param name="endRank"></param>
  408. /// <returns></returns>
  409. public static List<string> GetRangeFromSortedSet(string set, int beginRank, int endRank)
  410. {
  411. List<string> valueList = redisCli.GetRangeFromSortedSet(set, beginRank, endRank);
  412. return valueList;
  413. }
  414. /// <summary>
  415. /// 获得有序集合中,某个分数范围内的所有值,升序
  416. /// </summary>
  417. /// <param name="set"></param>
  418. /// <param name="beginScore"></param>
  419. /// <param name="endScore"></param>
  420. /// <returns></returns>
  421. public static List<string> GetRangeFromSortedSet(string set, double beginScore, double endScore)
  422. {
  423. List<string> valueList = redisCli.GetRangeFromSortedSetByHighestScore(set, beginScore, endScore);
  424. return valueList;
  425. }
  426. /// <summary>
  427. /// 获得有序集合中,某个分数范围内的所有值,降序
  428. /// </summary>
  429. /// <param name="set"></param>
  430. /// <param name="beginScore"></param>
  431. /// <param name="endScore"></param>
  432. /// <returns></returns>
  433. public static List<string> GetRangeFromSortedSetDesc(string set, double beginScore, double endScore)
  434. {
  435. List<string> vlaueList = redisCli.GetRangeFromSortedSetByLowestScore(set, beginScore, endScore);
  436. return vlaueList;
  437. }
  438. public static bool RemoveItemFromScoredSet(string setId, string value)
  439. {
  440. bool flag = redisCli.RemoveItemFromSortedSet(setId, value);
  441. return flag;
  442. }
  443. public static bool HasItemFromScoredSet(string setId, string value)
  444. {
  445. long index = redisCli.GetItemIndexInSortedSet(setId, value);
  446. return index < 0 ? false : true;
  447. }
  448. #endregion
  449. public void Dispose()
  450. {
  451. redisCli.Dispose();
  452. }
  453. }
  454. }