CustomRedisDbconn.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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 CustomRedisDbconn
  11. {
  12. public CSRedis.CSRedisClient csredis;
  13. public CustomRedisDbconn(string connstr, int Database = 0)
  14. {
  15. csredis = new CSRedis.CSRedisClient(connstr);
  16. }
  17. #region 设置单个字段
  18. public bool Set(string key, object value, int sec = -1)
  19. {
  20. return csredis.Set(key, value, sec);
  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 long DelFromList(string key, object value)
  132. {
  133. return csredis.LRem(key, 0, value);
  134. // return false;
  135. }
  136. #endregion
  137. #region 获取列表
  138. public List<T> GetList<T>(string key, int pageNum = 1, int pageSize = 10)
  139. {
  140. int start = (pageNum - 1) * pageSize;
  141. int end = start + pageSize - 1;
  142. T[] list = csredis.LRange<T>(key, start, end);
  143. return list.ToList();
  144. }
  145. #endregion
  146. #region 添加排序列表对象
  147. public long AddSort(string key, object value, decimal score)
  148. {
  149. return csredis.ZAdd(key, (score, value));
  150. // return 0;
  151. }
  152. #endregion
  153. #region 获取排序列表
  154. public List<T> GetSort<T>(string key, int pageNum = 1, int pageSize = 10)
  155. {
  156. int start = (pageNum - 1) * pageSize;
  157. int end = start + pageSize;
  158. string[] list = csredis.ZRangeByScore(key, start, end);
  159. List<T> lists = new List<T>();
  160. foreach (string record in list)
  161. {
  162. lists.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<T>(record));
  163. }
  164. return lists;
  165. }
  166. public List<T> GetSortDesc<T>(string key, int pageNum = 1, int pageSize = 10)
  167. {
  168. int start = (pageNum - 1) * pageSize;
  169. int end = start + pageSize;
  170. string[] list = csredis.ZRevRangeByScore(key, start, end);
  171. List<T> lists = new List<T>();
  172. foreach (string record in list)
  173. {
  174. lists.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<T>(record));
  175. }
  176. return lists;
  177. }
  178. #endregion
  179. public bool Remove(string key, long start, long end)
  180. {
  181. return csredis.LTrim(key, start, end);
  182. }
  183. public bool RemoveTop(string key, long count)
  184. {
  185. return RedisDbconn.Instance.Remove(key, count, RedisDbconn.Instance.Count(key) - 1); ;
  186. }
  187. public long Count(string key)
  188. {
  189. return csredis.LLen(key);
  190. }
  191. public void Clear(string pattern)
  192. {
  193. string[] keys = csredis.Keys(pattern);
  194. csredis.Del(keys);
  195. }
  196. public string[] GetKeys(string pattern)
  197. {
  198. string[] keys = csredis.Keys(pattern);
  199. return keys;
  200. }
  201. public bool Exists(string key)
  202. {
  203. return csredis.Exists(key);
  204. }
  205. public bool HExists(string key, string field)
  206. {
  207. return csredis.HExists(key, field);
  208. }
  209. public void SetExpire(string key, int expire)
  210. {
  211. csredis.Expire(key, expire); //秒为单位
  212. }
  213. /// <summary>
  214. /// 锁key
  215. /// </summary>
  216. private readonly string lockKey = "RedisLock";
  217. /// <summary>
  218. /// 锁的过期秒数
  219. /// </summary>
  220. private readonly int lockTime = 20;
  221. /// <summary>
  222. /// 续命线程取消令牌
  223. /// </summary>
  224. private CancellationTokenSource tokenSource = new CancellationTokenSource();
  225. /// <summary>
  226. /// 获取锁
  227. /// </summary>
  228. /// <param name="requestId">请求id保证释放锁时的客户端和加锁的客户端一致</param>
  229. /// <returns></returns>
  230. public bool GetLock(string requestId)
  231. {
  232. //设置key 设置过期时间20s
  233. while (true)
  234. {
  235. //设置key Redis2.6.12以上版本,可以用set获取锁。set可以实现setnx和expire,这个是原子操作
  236. if (csredis.Set(lockKey, requestId, lockTime, RedisExistence.Nx))
  237. {
  238. //设置成功后开启子线程为key续命
  239. CreateThredXm();
  240. return true;
  241. }
  242. }
  243. }
  244. /// <summary>
  245. /// 为锁续命(防止业务操作时间大于锁自动释放时间,锁被自动释放掉)
  246. /// </summary>
  247. void CreateThredXm()
  248. {
  249. Task.Run(() =>
  250. {
  251. while (true)
  252. {
  253. Thread.Sleep(10);
  254. //外部取消 退出子线程
  255. if (tokenSource.IsCancellationRequested)
  256. {
  257. return;
  258. }
  259. //查询key还有多少秒释放
  260. var Seconds = csredis.PTtl(lockKey) / 1000;
  261. //key还剩1/3秒时重设过期时间
  262. if (Seconds < (lockTime / 3))
  263. {
  264. //小于5秒则自动 重设过期时间
  265. csredis.Expire(lockKey, lockTime);
  266. }
  267. }
  268. }, tokenSource.Token);
  269. }
  270. /// <summary>
  271. /// 释放锁操作
  272. /// </summary>
  273. /// <param name="requestId">请求id保证释放锁时的客户端和加锁的客户端一致</param>
  274. public void ReleaseLock(string requestId)
  275. {
  276. //这里使用Lua脚本保证原子性操作
  277. string script = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
  278. "return redis.call('del', KEYS[1]) " +
  279. "else return 0 end";
  280. csredis.Eval(script, lockKey, requestId);
  281. //取消续命线程
  282. tokenSource.Cancel();
  283. }
  284. }
  285. }