Add project files.
This commit is contained in:
40
JSMR.Infrastructure/Caching/DistributedCacheAdapter.cs
Normal file
40
JSMR.Infrastructure/Caching/DistributedCacheAdapter.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
using JSMR.Application.Common.Caching;
|
||||
using Microsoft.Extensions.Caching.Distributed;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace JSMR.Infrastructure.Caching;
|
||||
|
||||
public class DistributedCacheAdapter(IDistributedCache distributedCache) : ICache
|
||||
{
|
||||
public async ValueTask<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default)
|
||||
{
|
||||
byte[]? bytes = await distributedCache.GetAsync(key, cancellationToken);
|
||||
|
||||
if (bytes == null)
|
||||
return default;
|
||||
|
||||
string json = Encoding.UTF8.GetString(bytes);
|
||||
|
||||
return JsonSerializer.Deserialize<T>(json);
|
||||
}
|
||||
|
||||
public async ValueTask SetAsync<T>(string key, T value, CacheEntryOptions options, CancellationToken cancellationToken = default)
|
||||
{
|
||||
string json = JsonSerializer.Serialize(value);
|
||||
byte[] bytes = Encoding.UTF8.GetBytes(json);
|
||||
|
||||
DistributedCacheEntryOptions distributedCacheOptions = new();
|
||||
|
||||
if (options.AbsoluteExpirationRelativeToNow != null)
|
||||
distributedCacheOptions.SetAbsoluteExpiration(options.AbsoluteExpirationRelativeToNow.Value);
|
||||
|
||||
if (options.AbsoluteExpiration != null)
|
||||
distributedCacheOptions.SetAbsoluteExpiration(options.AbsoluteExpiration.Value);
|
||||
|
||||
if (options.SlidingExpiration != null)
|
||||
distributedCacheOptions.SetSlidingExpiration(options.SlidingExpiration.Value);
|
||||
|
||||
await distributedCache.SetAsync(key, bytes, distributedCacheOptions, cancellationToken);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user