RedisDbconn.cs 9.4 KB

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