35 lines
1.1 KiB
C#
35 lines
1.1 KiB
C#
using Microsoft.Extensions.Caching.Distributed;
|
|
using System.Text.Json;
|
|
|
|
namespace IM.Commons
|
|
{
|
|
public class RedisCacheService : IRedisService
|
|
{
|
|
private readonly IDistributedCache _cache;
|
|
public RedisCacheService(IDistributedCache cache)
|
|
{
|
|
_cache = cache;
|
|
}
|
|
|
|
public async Task<T?> GetAsync<T>(string key)
|
|
{
|
|
var valueBytes = await _cache.GetAsync(key);
|
|
if (valueBytes is null || valueBytes.Length == 0) return default;
|
|
return JsonSerializer.Deserialize<T>(valueBytes);
|
|
}
|
|
|
|
public async Task RemoveAsync(string key) => await _cache.RemoveAsync(key);
|
|
|
|
public async Task SetAsync<T>(string key, T value, TimeSpan? expiration = null)
|
|
{
|
|
var options = new DistributedCacheEntryOptions
|
|
{
|
|
AbsoluteExpirationRelativeToNow = expiration ?? TimeSpan.FromHours(1)
|
|
};
|
|
var valueBytes = JsonSerializer.SerializeToUtf8Bytes(value);
|
|
await _cache.SetAsync(key, valueBytes, options);
|
|
}
|
|
|
|
}
|
|
}
|