|
| 1 | +using AspNetCoreHero.ThrowR; |
| 2 | +using Microsoft.Extensions.Caching.Distributed; |
| 3 | +using System; |
| 4 | +using System.Text.Json; |
| 5 | +using System.Threading; |
| 6 | +using System.Threading.Tasks; |
| 7 | + |
| 8 | +namespace AspNetCoreHero.Extensions.Caching |
| 9 | +{ |
| 10 | + public static class Extensions |
| 11 | + { |
| 12 | + public static async Task<T> GetAsync<T>(this IDistributedCache distributedCache, string cacheKey, CancellationToken token = default) |
| 13 | + { |
| 14 | + Throw.Exception.IfNull(distributedCache, nameof(distributedCache)); |
| 15 | + Throw.Exception.IfNull(cacheKey, nameof(cacheKey)); |
| 16 | + byte[] utf8Bytes = await distributedCache.GetAsync(cacheKey, token).ConfigureAwait(false); |
| 17 | + if (utf8Bytes != null) |
| 18 | + { |
| 19 | + return JsonSerializer.Deserialize<T>(utf8Bytes); |
| 20 | + } |
| 21 | + return default; |
| 22 | + } |
| 23 | + public static async Task RemoveAsync(this IDistributedCache distributedCache, string cacheKey, CancellationToken token = default) |
| 24 | + { |
| 25 | + Throw.Exception.IfNull(distributedCache, nameof(distributedCache)); |
| 26 | + Throw.Exception.IfNull(cacheKey, nameof(cacheKey)); |
| 27 | + await distributedCache.RemoveAsync(cacheKey, token).ConfigureAwait(false); |
| 28 | + } |
| 29 | + public static async Task SetAsync<T>(this IDistributedCache distributedCache, string cacheKey, T obj, int cacheExpirationInMinutes = 30, CancellationToken token = default) |
| 30 | + { |
| 31 | + Throw.Exception.IfNull(distributedCache, nameof(distributedCache)); |
| 32 | + Throw.Exception.IfNull(cacheKey, nameof(cacheKey)); |
| 33 | + Throw.Exception.IfNull(obj, nameof(obj)); |
| 34 | + DistributedCacheEntryOptions options = new DistributedCacheEntryOptions() |
| 35 | + .SetSlidingExpiration(TimeSpan.FromMinutes(cacheExpirationInMinutes)); |
| 36 | + byte[] utf8Bytes = JsonSerializer.SerializeToUtf8Bytes<T>(obj); |
| 37 | + await distributedCache.SetAsync(cacheKey, utf8Bytes, options, token).ConfigureAwait(false); |
| 38 | + } |
| 39 | + } |
| 40 | +} |
0 commit comments