RedisDbconn.cs 9.6 KB

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