2024-05-29 06:08:14 +03:00
|
|
|
|
using Microsoft.Extensions.Caching.Memory;
|
|
|
|
|
using Mirea.Api.Security.Common.Interfaces;
|
|
|
|
|
using System;
|
2024-06-21 21:44:34 +03:00
|
|
|
|
using System.Text.Json;
|
2024-05-29 06:11:29 +03:00
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
2024-05-29 06:08:14 +03:00
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
};
|
|
|
|
|
|
2024-06-21 21:44:34 +03:00
|
|
|
|
cache.Set(key, value as byte[] ?? JsonSerializer.SerializeToUtf8Bytes(value), options);
|
2024-05-29 06:08:14 +03:00
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Task<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default)
|
|
|
|
|
{
|
2024-06-28 01:49:45 +03:00
|
|
|
|
return Task.FromResult(
|
|
|
|
|
cache.TryGetValue(key, out byte[]? value) ?
|
|
|
|
|
JsonSerializer.Deserialize<T>(value) :
|
|
|
|
|
default
|
|
|
|
|
);
|
2024-05-29 06:08:14 +03:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Task RemoveAsync(string key, CancellationToken cancellationToken = default)
|
|
|
|
|
{
|
|
|
|
|
cache.Remove(key);
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
}
|