Cache.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace EasyTemplate.Tool.Util;
  7. public class Cache
  8. {
  9. /// <summary>
  10. ///
  11. /// </summary>
  12. /// <param name="key"></param>
  13. /// <param name="value"></param>
  14. public static void Set(string key, object value, string lockkey = "")
  15. {
  16. var type = Setting.Get<string>("Cache:CacheType");
  17. if ((type?.ToLower().Contains("redis")).Value)
  18. {
  19. if (!string.IsNullOrWhiteSpace(lockkey))
  20. {
  21. Redis.SetWithLockAsync(lockkey, key, value);
  22. }
  23. else
  24. {
  25. Redis.SetAsync(key, value);
  26. }
  27. }
  28. else
  29. {
  30. MemoryCache.Set(key, value);
  31. }
  32. }
  33. /// <summary>
  34. ///
  35. /// </summary>
  36. /// <param name="key"></param>
  37. /// <param name="value"></param>
  38. public static async Task Increase(string key, int value = 1, string lockkey = "")
  39. {
  40. var current = await Get<int>(key);
  41. var type = Setting.Get<string>("Cache:CacheType");
  42. if ((type?.ToLower().Contains("redis")).Value)
  43. {
  44. if (!string.IsNullOrWhiteSpace(lockkey))
  45. {
  46. await Redis.SetWithLockAsync(lockkey, key, current+value);
  47. }
  48. else
  49. {
  50. await Redis.SetAsync(key, current + value);
  51. }
  52. }
  53. else
  54. {
  55. MemoryCache.Set(key, current + value);
  56. }
  57. }
  58. /// <summary>
  59. ///
  60. /// </summary>
  61. /// <typeparam name="T"></typeparam>
  62. /// <param name="key"></param>
  63. /// <param name="value"></param>
  64. public static async Task<T> Get<T>(string key)
  65. {
  66. var type = Setting.Get<string>("Cache:CacheType");
  67. if ((type?.ToLower().Contains("redis")).Value)
  68. {
  69. return await Redis.GetAsync<T>(key);
  70. }
  71. else
  72. {
  73. return MemoryCache.GetT<T>(key);
  74. }
  75. }
  76. /// <summary>
  77. ///
  78. /// </summary>
  79. /// <typeparam name="T"></typeparam>
  80. /// <param name="key"></param>
  81. /// <param name="value"></param>
  82. public static async Task<bool> Exist(string key)
  83. {
  84. var type = Setting.Get<string>("Cache:CacheType");
  85. if ((type?.ToLower().Contains("redis")).Value)
  86. {
  87. return await Redis.ExistsAsync(key);
  88. }
  89. else
  90. {
  91. return MemoryCache.Exists(key);
  92. }
  93. }
  94. }