feat(dal): IRedisCacheService
This commit is contained in:
63
PARR.DAL/CacheServices/RedisCacheService.cs
Normal file
63
PARR.DAL/CacheServices/RedisCacheService.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using Microsoft.Extensions.Caching.Distributed;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace PARR.DAL.CacheServices
|
||||
{
|
||||
internal class RedisCacheService : IRedisCacheService
|
||||
{
|
||||
private readonly IDistributedCache cache;
|
||||
|
||||
public RedisCacheService(IDistributedCache cache)
|
||||
{
|
||||
this.cache = cache;
|
||||
}
|
||||
|
||||
public async Task<T?> GetCachedDataAsync<T>(string key)
|
||||
{
|
||||
var jsonData = await cache.GetStringAsync(key);
|
||||
|
||||
if (jsonData == null)
|
||||
return default(T);
|
||||
|
||||
return JsonSerializer.Deserialize<T>(jsonData);
|
||||
}
|
||||
|
||||
|
||||
public T? GetCachedData<T>(string key)
|
||||
{
|
||||
var jsonData = cache.GetString(key);
|
||||
|
||||
if (jsonData == null)
|
||||
return default(T);
|
||||
|
||||
return JsonSerializer.Deserialize<T>(jsonData);
|
||||
}
|
||||
|
||||
|
||||
public void SetCachedData<T>(string key, T data, TimeSpan cacheDuration)
|
||||
{
|
||||
var options = new DistributedCacheEntryOptions
|
||||
{
|
||||
AbsoluteExpirationRelativeToNow = cacheDuration
|
||||
};
|
||||
|
||||
var jsonData = JsonSerializer.Serialize(data);
|
||||
cache.SetString(key, jsonData, options);
|
||||
}
|
||||
|
||||
|
||||
public async Task SetCachedDataAsync<T>(string key, T data, TimeSpan cacheDuration)
|
||||
{
|
||||
var options = new DistributedCacheEntryOptions
|
||||
{
|
||||
AbsoluteExpirationRelativeToNow = cacheDuration
|
||||
};
|
||||
|
||||
var jsonData = JsonSerializer.Serialize(data);
|
||||
await cache.SetStringAsync(key, jsonData, options);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user