RedisCacheService.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. using Microsoft.Extensions.Caching.Redis;
  2. using Newtonsoft.Json;
  3. using StackExchange.Redis;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace TEAMModelOS.SDK.Module.Cache
  10. {
  11. public class RedisCacheService : ICacheService,IDisposable
  12. {
  13. protected IDatabase _cache;
  14. private ConnectionMultiplexer _connection;
  15. private readonly string _instance;
  16. public RedisCacheService(RedisCacheOptions options, int database = 0)
  17. {
  18. _connection = ConnectionMultiplexer.Connect(options.Configuration);
  19. _cache = _connection.GetDatabase(database);
  20. _instance = options.InstanceName;
  21. }
  22. public string GetKeyForRedis(string key)
  23. {
  24. return _instance + key;
  25. }/// <summary>
  26. /// 验证缓存项是否存在
  27. /// </summary>
  28. /// <param name="key">缓存Key</param>
  29. /// <returns></returns>
  30. public bool Exists(string key)
  31. {
  32. if (key == null)
  33. {
  34. throw new ArgumentNullException(nameof(key));
  35. }
  36. return _cache.KeyExists(GetKeyForRedis(key));
  37. }/// <summary>
  38. /// 添加缓存
  39. /// </summary>
  40. /// <param name="key">缓存Key</param>
  41. /// <param name="value">缓存Value</param>
  42. /// <returns></returns>
  43. public bool Add(string key, object value)
  44. {
  45. if (key == null)
  46. {
  47. throw new ArgumentNullException(nameof(key));
  48. }
  49. return _cache.StringSet(GetKeyForRedis(key), Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)));
  50. }
  51. /// <summary>
  52. /// 添加缓存
  53. /// </summary>
  54. /// <param name="key">缓存Key</param>
  55. /// <param name="value">缓存Value</param>
  56. /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间,Redis中无效)</param>
  57. /// <param name="expiressAbsoulte">绝对过期时长</param>
  58. /// <returns></returns>
  59. public bool Add(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
  60. {
  61. if (key == null)
  62. {
  63. throw new ArgumentNullException(nameof(key));
  64. }
  65. return _cache.StringSet(GetKeyForRedis(key), Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)), expiressAbsoulte);
  66. }
  67. /// <summary>
  68. /// 添加缓存
  69. /// </summary>
  70. /// <param name="key">缓存Key</param>
  71. /// <param name="value">缓存Value</param>
  72. /// <param name="expiresIn">缓存时长</param>
  73. /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间,Redis中无效)</param>
  74. /// <returns></returns>
  75. public bool Add(string key, object value, TimeSpan expiresIn, bool isSliding = false)
  76. {
  77. if (key == null)
  78. {
  79. throw new ArgumentNullException(nameof(key));
  80. }
  81. return _cache.StringSet(GetKeyForRedis(key), Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value)), expiresIn);
  82. }/// <summary>
  83. /// 删除缓存
  84. /// </summary>
  85. /// <param name="key">缓存Key</param>
  86. /// <returns></returns>
  87. public bool Remove(string key)
  88. {
  89. if (key == null)
  90. {
  91. throw new ArgumentNullException(nameof(key));
  92. }
  93. return _cache.KeyDelete(GetKeyForRedis(key));
  94. }
  95. /// <summary>
  96. /// 批量删除缓存
  97. /// </summary>
  98. /// <param name="key">缓存Key集合</param>
  99. /// <returns></returns>
  100. public void RemoveAll(IEnumerable<string> keys)
  101. {
  102. if (keys == null)
  103. {
  104. throw new ArgumentNullException(nameof(keys));
  105. }
  106. keys.ToList().ForEach(item => Remove(item));
  107. }
  108. /// <summary>
  109. /// 获取缓存
  110. /// </summary>
  111. /// <param name="key">缓存Key</param>
  112. /// <returns></returns>
  113. public T Get<T>(string key) where T : class
  114. {
  115. if (key == null)
  116. {
  117. throw new ArgumentNullException(nameof(key));
  118. }
  119. var value = _cache.StringGet(GetKeyForRedis(key));
  120. if (!value.HasValue)
  121. {
  122. return default(T);
  123. }
  124. return JsonConvert.DeserializeObject<T>(value);
  125. }
  126. /// <summary>
  127. /// 获取缓存
  128. /// </summary>
  129. /// <param name="key">缓存Key</param>
  130. /// <returns></returns>
  131. public object Get(string key)
  132. {
  133. if (key == null)
  134. {
  135. throw new ArgumentNullException(nameof(key));
  136. }
  137. var value = _cache.StringGet(GetKeyForRedis(key));
  138. if (!value.HasValue)
  139. {
  140. return null;
  141. }
  142. return JsonConvert.DeserializeObject(value);
  143. } /// <summary>
  144. /// 获取缓存集合
  145. /// </summary>
  146. /// <param name="keys">缓存Key集合</param>
  147. /// <returns></returns>
  148. public IDictionary<string, object> GetAll(IEnumerable<string> keys)
  149. {
  150. if (keys == null)
  151. {
  152. throw new ArgumentNullException(nameof(keys));
  153. }
  154. var dict = new Dictionary<string, object>();
  155. keys.ToList().ForEach(item => dict.Add(item, Get(GetKeyForRedis(item))));
  156. return dict;
  157. }
  158. /// <summary>
  159. /// 修改缓存
  160. /// </summary>
  161. /// <param name="key">缓存Key</param>
  162. /// <param name="value">新的缓存Value</param>
  163. /// <returns></returns>
  164. public bool Replace(string key, object value)
  165. {
  166. if (key == null)
  167. {
  168. throw new ArgumentNullException(nameof(key));
  169. }
  170. if (Exists(key))
  171. if (!Remove(key))
  172. return false;
  173. return Add(key, value);
  174. }
  175. /// <summary>
  176. /// 修改缓存
  177. /// </summary>
  178. /// <param name="key">缓存Key</param>
  179. /// <param name="value">新的缓存Value</param>
  180. /// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
  181. /// <param name="expiressAbsoulte">绝对过期时长</param>
  182. /// <returns></returns>
  183. public bool Replace(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
  184. {
  185. if (key == null)
  186. {
  187. throw new ArgumentNullException(nameof(key));
  188. }
  189. if (Exists(key))
  190. if (!Remove(key))
  191. return false;
  192. return Add(key, value, expiresSliding, expiressAbsoulte);
  193. }
  194. /// <summary>
  195. /// 修改缓存
  196. /// </summary>
  197. /// <param name="key">缓存Key</param>
  198. /// <param name="value">新的缓存Value</param>
  199. /// <param name="expiresIn">缓存时长</param>
  200. /// <param name="isSliding">是否滑动过期(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
  201. /// <returns></returns>
  202. public bool Replace(string key, object value, TimeSpan expiresIn, bool isSliding = false)
  203. {
  204. if (key == null)
  205. {
  206. throw new ArgumentNullException(nameof(key));
  207. }
  208. if (Exists(key))
  209. if (!Remove(key)) return false;
  210. return Add(key, value, expiresIn, isSliding);
  211. }
  212. public void Dispose()
  213. {
  214. if (_connection != null)
  215. _connection.Dispose();
  216. GC.SuppressFinalize(this);
  217. }
  218. public async Task<bool> ExistsAsync(string key)
  219. {
  220. return await Task.Run(() => Exists(key));
  221. }
  222. public async Task<bool> AddAsync(string key, object value)
  223. {
  224. return await Task.Run(() => Add(key, value));
  225. }
  226. public async Task<bool> AddAsync(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
  227. {
  228. return await Task.Run(() => Add(key, value, expiresSliding, expiressAbsoulte));
  229. }
  230. public async Task<bool> AddAsync(string key, object value, TimeSpan expiresIn, bool isSliding = false)
  231. {
  232. return await Task.Run(() => Add(key, value, expiresIn, isSliding));
  233. }
  234. public async Task<bool> RemoveAsync(string key)
  235. {
  236. return await Task.Run(() => Remove(key));
  237. }
  238. public async Task RemoveAllAsync(IEnumerable<string> keys)
  239. {
  240. await Task.Run(() => RemoveAll(keys));
  241. }
  242. public async Task<T> GetAsync<T>(string key) where T : class
  243. {
  244. return await Task.Run(() => Get<T>(key));
  245. }
  246. public async Task<object> GetAsync(string key)
  247. {
  248. return await Task.Run(() => Get(key));
  249. }
  250. public async Task<IDictionary<string, object>> GetAllAsync(IEnumerable<string> keys)
  251. {
  252. return await Task.Run(() => GetAll(keys));
  253. }
  254. public async Task<bool> ReplaceAsync(string key, object value)
  255. {
  256. return await Task.Run(() => Replace(key, value));
  257. }
  258. public async Task<bool> ReplaceAsync(string key, object value, TimeSpan expiresSliding, TimeSpan expiressAbsoulte)
  259. {
  260. return await Task.Run(() => Replace(key, value, expiresSliding, expiressAbsoulte));
  261. }
  262. public async Task<bool> ReplaceAsync(string key, object value, TimeSpan expiresIn, bool isSliding = false)
  263. {
  264. return await Task.Run(() => Replace(key, value, expiresIn, isSliding));
  265. }
  266. }
  267. }