CSRedisCacheService.cs 9.5 KB

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