RedisDbconn.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using CSRedis;
  6. using Library;
  7. using System.Linq;
  8. namespace MySystem
  9. {
  10. public class RedisDbconn
  11. {
  12. public readonly static RedisDbconn Instance = new RedisDbconn();
  13. public static CSRedis.CSRedisClient csredis;
  14. private RedisDbconn()
  15. {
  16. }
  17. #region 设置单个字段
  18. public bool Set(string key, object value)
  19. {
  20. return csredis.Set(key, value);
  21. // return false;
  22. }
  23. #endregion
  24. #region 整数累加
  25. public long AddInt(string key, long value = 1)
  26. {
  27. return csredis.IncrBy(key, value);
  28. // return 0;
  29. }
  30. #endregion
  31. #region 数字累加
  32. public decimal AddNumber(string key, decimal value = 1)
  33. {
  34. return csredis.IncrByFloat(key, value);
  35. // return 0;
  36. }
  37. #endregion
  38. #region 获取单个字段
  39. public T Get<T>(string key)
  40. {
  41. return csredis.Get<T>(key);
  42. }
  43. #endregion
  44. #region 设置散列字段
  45. public bool HSet(string key, string field, object value)
  46. {
  47. return csredis.HSet(key, field, value);
  48. // return false;
  49. }
  50. #endregion
  51. #region 散列整数累加
  52. public long HAddInt(string key, string field, long value = 1)
  53. {
  54. return csredis.HIncrBy(key, field, value);
  55. // return 0;
  56. }
  57. #endregion
  58. #region 散列数字累加
  59. public decimal HAddNumber(string key, string field, decimal value = 1)
  60. {
  61. return csredis.HIncrByFloat(key, field, value);
  62. // return 0;
  63. }
  64. #endregion
  65. #region 获取散列元素
  66. public T HGet<T>(string key, string field)
  67. {
  68. return csredis.HGet<T>(key, field);
  69. }
  70. #endregion
  71. #region 获取散列所有元素
  72. public Dictionary<string, T> HGetAll<T>(string key)
  73. {
  74. return csredis.HGetAll<T>(key);
  75. }
  76. #endregion
  77. #region 添加列表对象
  78. public long AddList(string key, object value)
  79. {
  80. return csredis.LPush(key, value);
  81. // return 0;
  82. }
  83. public long AddList(string key, object[] value)
  84. {
  85. return csredis.LPush(key, value);
  86. // return 0;
  87. }
  88. public long AddRightList(string key, object value)
  89. {
  90. return csredis.RPush(key, value);
  91. // return 0;
  92. }
  93. public T RPop<T>(string key)
  94. {
  95. return csredis.RPop<T>(key);
  96. }
  97. #endregion
  98. #region 添加集合对象
  99. public long SAdd(string key, object value)
  100. {
  101. return csredis.SAdd(key, value);
  102. // return 0;
  103. }
  104. public long SAdd(string key, object[] value)
  105. {
  106. return csredis.SAdd(key, value);
  107. // return 0;
  108. }
  109. #endregion
  110. #region 获取集合对象
  111. public T[] SGetList<T>(string key)
  112. {
  113. return csredis.SMembers<T>(key);
  114. }
  115. #endregion
  116. #region 判断元素是否存在
  117. public bool SIsMember(string key, object value)
  118. {
  119. return csredis.SIsMember(key, value);
  120. }
  121. #endregion
  122. #region 修改列表对象
  123. public bool SetList(string key, int index, object value)
  124. {
  125. long itemindex = csredis.LLen(key) - index - 1;
  126. return csredis.LSet(key, itemindex, value);
  127. // return false;
  128. }
  129. #endregion
  130. #region 获取列表
  131. public List<T> GetList<T>(string key, int pageNum = 1, int pageSize = 10)
  132. {
  133. int start = (pageNum - 1) * pageSize;
  134. int end = start + pageSize - 1;
  135. T[] list = csredis.LRange<T>(key, start, end);
  136. return list.ToList();
  137. }
  138. #endregion
  139. #region 添加排序列表对象
  140. public long AddSort(string key, object value, decimal score)
  141. {
  142. return csredis.ZAdd(key, (score, value));
  143. // return 0;
  144. }
  145. #endregion
  146. #region 获取排序列表
  147. public List<T> GetSort<T>(string key, int pageNum = 1, int pageSize = 10)
  148. {
  149. int start = (pageNum - 1) * pageSize;
  150. int end = start + pageSize;
  151. string[] list = csredis.ZRangeByScore(key, start, end);
  152. List<T> lists = new List<T>();
  153. foreach (string record in list)
  154. {
  155. lists.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<T>(record));
  156. }
  157. return lists;
  158. }
  159. public List<T> GetSortDesc<T>(string key, int pageNum = 1, int pageSize = 10)
  160. {
  161. int start = (pageNum - 1) * pageSize;
  162. int end = start + pageSize;
  163. string[] list = csredis.ZRevRangeByScore(key, start, end);
  164. List<T> lists = new List<T>();
  165. foreach (string record in list)
  166. {
  167. lists.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<T>(record));
  168. }
  169. return lists;
  170. }
  171. #endregion
  172. public bool Remove(string key, long start, long end)
  173. {
  174. return csredis.LTrim(key, start, end);
  175. }
  176. public bool RemoveTop(string key, long count)
  177. {
  178. return RedisDbconn.Instance.Remove(key, count, RedisDbconn.Instance.Count(key) - 1); ;
  179. }
  180. public long Count(string key)
  181. {
  182. return csredis.LLen(key);
  183. }
  184. public void Clear(string pattern)
  185. {
  186. string[] keys = csredis.Keys(pattern);
  187. csredis.Del(keys);
  188. }
  189. public string[] GetKeys(string pattern)
  190. {
  191. string[] keys = csredis.Keys(pattern);
  192. return keys;
  193. }
  194. public bool Exists(string key)
  195. {
  196. return csredis.Exists(key);
  197. }
  198. public bool HExists(string key, string field)
  199. {
  200. return csredis.HExists(key, field);
  201. }
  202. public void SetExpire(string key, int expire)
  203. {
  204. csredis.Expire(key, expire); //秒为单位
  205. }
  206. /// <summary>
  207. /// 锁key
  208. /// </summary>
  209. private readonly string lockKey = "RedisLock";
  210. /// <summary>
  211. /// 锁的过期秒数
  212. /// </summary>
  213. private readonly int lockTime = 20;
  214. /// <summary>
  215. /// 续命线程取消令牌
  216. /// </summary>
  217. private CancellationTokenSource tokenSource = new CancellationTokenSource();
  218. /// <summary>
  219. /// 获取锁
  220. /// </summary>
  221. /// <param name="requestId">请求id保证释放锁时的客户端和加锁的客户端一致</param>
  222. /// <returns></returns>
  223. public bool GetLock(string requestId)
  224. {
  225. //设置key 设置过期时间20s
  226. while (true)
  227. {
  228. //设置key Redis2.6.12以上版本,可以用set获取锁。set可以实现setnx和expire,这个是原子操作
  229. if (csredis.Set(lockKey, requestId, lockTime, RedisExistence.Nx))
  230. {
  231. //设置成功后开启子线程为key续命
  232. CreateThredXm();
  233. return true;
  234. }
  235. }
  236. }
  237. /// <summary>
  238. /// 为锁续命(防止业务操作时间大于锁自动释放时间,锁被自动释放掉)
  239. /// </summary>
  240. void CreateThredXm()
  241. {
  242. Task.Run(() =>
  243. {
  244. while (true)
  245. {
  246. Thread.Sleep(10);
  247. //外部取消 退出子线程
  248. if (tokenSource.IsCancellationRequested)
  249. {
  250. return;
  251. }
  252. //查询key还有多少秒释放
  253. var Seconds = csredis.PTtl(lockKey) / 1000;
  254. //key还剩1/3秒时重设过期时间
  255. if (Seconds < (lockTime / 3))
  256. {
  257. //小于5秒则自动 重设过期时间
  258. csredis.Expire(lockKey, lockTime);
  259. }
  260. }
  261. }, tokenSource.Token);
  262. }
  263. /// <summary>
  264. /// 释放锁操作
  265. /// </summary>
  266. /// <param name="requestId">请求id保证释放锁时的客户端和加锁的客户端一致</param>
  267. public void ReleaseLock(string requestId)
  268. {
  269. //这里使用Lua脚本保证原子性操作
  270. string script = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
  271. "return redis.call('del', KEYS[1]) " +
  272. "else return 0 end";
  273. csredis.Eval(script, lockKey, requestId);
  274. //取消续命线程
  275. tokenSource.Cancel();
  276. }
  277. }
  278. }