61 lines
1.6 KiB
C#
61 lines
1.6 KiB
C#
using System.Text.Json;
|
|
using LexWells.Infrastructure.Common.Interfaces;
|
|
using Microsoft.Extensions.Caching.Distributed;
|
|
|
|
namespace LexWells.Infrastructure.Common.Services;
|
|
|
|
public class RedisCacheService : ICacheService
|
|
{
|
|
private readonly IDistributedCache _cache;
|
|
|
|
public RedisCacheService(IDistributedCache cache)
|
|
{
|
|
_cache = cache;
|
|
}
|
|
|
|
public async Task<IEnumerable<T>?> GetCollectionAsync<T, TConcrete>(string key)
|
|
where TConcrete : T
|
|
{
|
|
var cachedData = await _cache.GetStringAsync(key);
|
|
|
|
if (string.IsNullOrEmpty(cachedData)) return null;
|
|
|
|
var result = JsonSerializer.Deserialize<HashSet<TConcrete>>(cachedData);
|
|
return result?.Cast<T>();
|
|
}
|
|
|
|
public async Task<T?> GetAsync<T>(string key)
|
|
{
|
|
var cachedData = await _cache.GetStringAsync(key);
|
|
|
|
// Explicitly return null if Redis has NOTHING
|
|
if (string.IsNullOrWhiteSpace(cachedData))
|
|
{
|
|
return default;
|
|
}
|
|
|
|
try {
|
|
return JsonSerializer.Deserialize<T>(cachedData);
|
|
}
|
|
catch {
|
|
return default;
|
|
}
|
|
}
|
|
|
|
public async Task SetAsync<T>(string key, T value, TimeSpan? expiration = null)
|
|
{
|
|
var options = new DistributedCacheEntryOptions
|
|
{
|
|
AbsoluteExpirationRelativeToNow = expiration ?? TimeSpan.FromHours(1)
|
|
};
|
|
|
|
string dataToStore = value is string s ? s : JsonSerializer.Serialize(value);
|
|
|
|
await _cache.SetStringAsync(key, dataToStore, options);
|
|
}
|
|
|
|
public async Task RemoveAsync(string key)
|
|
{
|
|
await _cache.RemoveAsync(key);
|
|
}
|
|
} |