0
0

RedisCache.cs 2.8 KB

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