RedisDbconn.cs 9.4 KB

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