CustomRedisDbconn.cs 9.6 KB

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