feat: add cache implementations depending on the type

This commit is contained in:
Polianin Nikita 2024-05-29 06:08:14 +03:00
parent 2efdc6dbfe
commit 9287acf7d2
2 changed files with 66 additions and 0 deletions

View File

@ -0,0 +1,32 @@
using Microsoft.Extensions.Caching.Distributed;
using Mirea.Api.Security.Common.Interfaces;
using System.Text.Json;
using System.Threading.Tasks;
using System.Threading;
using System;
namespace Mirea.Api.Endpoint.Common.Services.Security;
public class DistributedCacheService(IDistributedCache cache) : ICacheService
{
public async Task SetAsync<T>(string key, T value, TimeSpan? absoluteExpirationRelativeToNow = null, TimeSpan? slidingExpiration = null, CancellationToken cancellationToken = default)
{
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = absoluteExpirationRelativeToNow,
SlidingExpiration = slidingExpiration
};
var serializedValue = JsonSerializer.SerializeToUtf8Bytes(value);
await cache.SetAsync(key, serializedValue, options, cancellationToken);
}
public async Task<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default)
{
var cachedValue = await cache.GetAsync(key, cancellationToken);
return cachedValue == null ? default : JsonSerializer.Deserialize<T>(cachedValue);
}
public Task RemoveAsync(string key, CancellationToken cancellationToken = default) =>
cache.RemoveAsync(key, cancellationToken);
}

View File

@ -0,0 +1,34 @@
using Microsoft.Extensions.Caching.Memory;
using Mirea.Api.Security.Common.Interfaces;
using System.Threading.Tasks;
using System.Threading;
using System;
namespace Mirea.Api.Endpoint.Common.Services.Security;
public class MemoryCacheService(IMemoryCache cache) : ICacheService
{
public Task SetAsync<T>(string key, T value, TimeSpan? absoluteExpirationRelativeToNow = null, TimeSpan? slidingExpiration = null, CancellationToken cancellationToken = default)
{
var options = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = absoluteExpirationRelativeToNow,
SlidingExpiration = slidingExpiration
};
cache.Set(key, value, options);
return Task.CompletedTask;
}
public Task<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default)
{
cache.TryGetValue(key, out T? value);
return Task.FromResult(value);
}
public Task RemoveAsync(string key, CancellationToken cancellationToken = default)
{
cache.Remove(key);
return Task.CompletedTask;
}
}