DistributedCacheExt.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Text;
  3. using Masuit.Tools.Systems;
  4. using Microsoft.Extensions.Caching.Distributed;
  5. using Newtonsoft.Json;
  6. namespace Masuit.Tools.AspNetCore.Extensions;
  7. /// <summary>
  8. ///
  9. /// </summary>
  10. public static class DistributedCacheExt
  11. {
  12. public static T GetOrAdd<T>(this IDistributedCache cache, string key, Func<T> valueFactory)
  13. {
  14. var bytes = cache.Get(key);
  15. if (bytes is null)
  16. {
  17. var value = new NullObject<T>(valueFactory());
  18. bytes = Encoding.UTF8.GetBytes(value.ToJsonString());
  19. cache.Set(key, bytes);
  20. return value;
  21. }
  22. return JsonConvert.DeserializeObject<NullObject<T>>(Encoding.UTF8.GetString(bytes));
  23. }
  24. public static T Get<T>(this IDistributedCache cache, string key)
  25. {
  26. var bytes = cache.Get(key);
  27. if (bytes is null)
  28. {
  29. return default;
  30. }
  31. return JsonConvert.DeserializeObject<NullObject<T>>(Encoding.UTF8.GetString(bytes));
  32. }
  33. public static void Set<T>(this IDistributedCache cache, string key, T value)
  34. {
  35. cache.Set(key, Encoding.UTF8.GetBytes(new NullObject<T>(value).ToJsonString()), new DistributedCacheEntryOptions());
  36. }
  37. public static void Set<T>(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions options)
  38. {
  39. cache.Set(key, Encoding.UTF8.GetBytes(new NullObject<T>(value).ToJsonString()), options);
  40. }
  41. public static T GetOrAdd<T>(this IDistributedCache cache, string key, T value)
  42. {
  43. var bytes = cache.Get(key);
  44. if (bytes is null)
  45. {
  46. bytes = Encoding.UTF8.GetBytes(new NullObject<T>(value).ToJsonString());
  47. cache.Set(key, bytes);
  48. return value;
  49. }
  50. return JsonConvert.DeserializeObject<NullObject<T>>(Encoding.UTF8.GetString(bytes));
  51. }
  52. public static void AddOrUpdate<T>(this IDistributedCache cache, string key, T addValue, Func<T, T> updateFunc)
  53. {
  54. var bytes = cache.Get(key);
  55. if (bytes is null)
  56. {
  57. bytes = Encoding.UTF8.GetBytes(new NullObject<T>(addValue).ToJsonString());
  58. cache.Set(key, bytes);
  59. return;
  60. }
  61. var value = new NullObject<T>(updateFunc(JsonConvert.DeserializeObject<NullObject<T>>(Encoding.UTF8.GetString(bytes))));
  62. cache.Set(key, Encoding.UTF8.GetBytes(value.ToJsonString()));
  63. }
  64. }