RedisCacheTool.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using FreeRedis;
  2. using System;
  3. using System.Text.RegularExpressions;
  4. using System.Threading.Tasks;
  5. using ZhonTai.Common.Extensions;
  6. namespace ZhonTai.Admin.Tools.Cache;
  7. /// <summary>
  8. /// Redis缓存
  9. /// </summary>
  10. public partial class RedisCacheTool : ICacheTool
  11. {
  12. [GeneratedRegex("\\{.*\\}")]
  13. private static partial Regex PatternRegex();
  14. private readonly RedisClient _redisClient;
  15. public RedisCacheTool(RedisClient redisClient)
  16. {
  17. _redisClient = redisClient;
  18. }
  19. public long Del(params string[] key)
  20. {
  21. return _redisClient.Del(key);
  22. }
  23. public Task<long> DelAsync(params string[] key)
  24. {
  25. return _redisClient.DelAsync(key);
  26. }
  27. public async Task<long> DelByPatternAsync(string pattern)
  28. {
  29. if (pattern.IsNull())
  30. return default;
  31. pattern = PatternRegex().Replace(pattern, "*");
  32. var keys = await _redisClient.KeysAsync(pattern);
  33. if (keys != null && keys.Length > 0)
  34. {
  35. return await _redisClient.DelAsync(keys);
  36. }
  37. return default;
  38. }
  39. public bool Exists(string key)
  40. {
  41. return _redisClient.Exists(key);
  42. }
  43. public Task<bool> ExistsAsync(string key)
  44. {
  45. return _redisClient.ExistsAsync(key);
  46. }
  47. public string Get(string key)
  48. {
  49. return _redisClient.Get(key);
  50. }
  51. public T Get<T>(string key)
  52. {
  53. return _redisClient.Get<T>(key);
  54. }
  55. public Task<string> GetAsync(string key)
  56. {
  57. return _redisClient.GetAsync(key);
  58. }
  59. public Task<T> GetAsync<T>(string key)
  60. {
  61. return _redisClient.GetAsync<T>(key);
  62. }
  63. public void Set(string key, object value)
  64. {
  65. _redisClient.Set(key, value);
  66. }
  67. public void Set(string key, object value, TimeSpan expire)
  68. {
  69. _redisClient.Set(key, value, expire);
  70. }
  71. public Task SetAsync(string key, object value, TimeSpan? expire = null)
  72. {
  73. return _redisClient.SetAsync(key, value, expire.HasValue ? expire.Value.TotalSeconds.ToInt() : 0);
  74. }
  75. public async Task<T> GetOrSetAsync<T>(string key, Func<Task<T>> func, TimeSpan? expire = null)
  76. {
  77. if (await _redisClient.ExistsAsync(key))
  78. {
  79. try
  80. {
  81. return await _redisClient.GetAsync<T>(key);
  82. }
  83. catch
  84. {
  85. await _redisClient.DelAsync(key);
  86. }
  87. }
  88. var result = await func.Invoke();
  89. await _redisClient.SetAsync(key, result, expire.HasValue ? expire.Value.TotalSeconds.ToInt() : 0);
  90. return result;
  91. }
  92. }