DistributedCacheExtensions.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using Microsoft.Extensions.Caching.Distributed;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace XYY.Common.Standard
  8. {
  9. public static class DistributedCacheExtensions
  10. {
  11. /// <summary>
  12. /// 异步获取缓存数据
  13. /// </summary>
  14. /// <typeparam name="T">获取数据类型</typeparam>
  15. /// <param name="cache"></param>
  16. /// <param name="key">Key</param>
  17. /// <param name="getData">异步委托</param>
  18. /// <returns></returns>
  19. public static async Task<T> GetAsync<T>(this IDistributedCache cache, string key, Func<Task<T>> getData, DistributedCacheEntryOptions options = null)
  20. {
  21. var str = await cache.GetStringAsync(key);
  22. if (string.IsNullOrEmpty(str))
  23. {
  24. var data = await getData();
  25. string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
  26. str = json;
  27. await cache.SetStringAsync(key, json);
  28. return data;
  29. }
  30. else
  31. {
  32. return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
  33. }
  34. }
  35. public static async Task<T> GetAsync<T>(this IDistributedCache cache, string key, Func<Task<T>> getData)
  36. {
  37. return await GetAsync(cache,key,getData,null);
  38. }
  39. }
  40. }