CacheExtensions.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. using Microsoft.Extensions.Caching.Distributed;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.IO.Compression;
  8. namespace SMP.Common.Extensions
  9. {
  10. public static class CacheExtensions
  11. {
  12. public static Task SetAsync(this IDistributedCache cache, string key, object data, DistributedCacheEntryOptions options, CancellationToken token = default)
  13. {
  14. string josnValue = Newtonsoft.Json.JsonConvert.SerializeObject(data);
  15. var bytes = UTF8Encoding.UTF8.GetBytes(josnValue);
  16. return cache.SetAsync(key, bytes, options, token);
  17. }
  18. public static async Task<T?> GetAsync<T>(this IDistributedCache cache, string key, CancellationToken token = default)
  19. {
  20. var cacheV = await cache.GetAsync(key, token);
  21. if (cacheV == null)
  22. {
  23. return default;
  24. }
  25. string orijson = System.Text.UTF8Encoding.UTF8.GetString(cacheV);
  26. var a = await Task<T>.Run(() => Newtonsoft.Json.JsonConvert.DeserializeObject<T>(orijson));
  27. return a;
  28. }
  29. }
  30. }