1
0

RedisCache.cs 2.8 KB

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