DistributedCacheExt.cs 2.4 KB

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