RedisDbconn.cs 9.7 KB

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