添加项目文件。
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user