37 lines
1.1 KiB
C#
37 lines
1.1 KiB
C#
|
using System;
|
||
|
using System.Collections.Generic;
|
||
|
using System.Linq;
|
||
|
using System.Threading.Tasks;
|
||
|
using StackExchange.Redis;
|
||
|
using System.Text.Json;
|
||
|
|
||
|
namespace Cloud.Services.Cache
|
||
|
{
|
||
|
public class RedisCacheService : IRedisCacheService
|
||
|
{
|
||
|
private readonly IConnectionMultiplexer _connectionMultiplexer;
|
||
|
|
||
|
public RedisCacheService(IConnectionMultiplexer connectionMultiplexer)
|
||
|
{
|
||
|
_connectionMultiplexer = connectionMultiplexer;
|
||
|
}
|
||
|
|
||
|
public async Task SetCacheAsync<T>(string key, T value, TimeSpan? expiry = null)
|
||
|
{
|
||
|
var database = _connectionMultiplexer.GetDatabase();
|
||
|
var serializedValue = JsonSerializer.Serialize(value);
|
||
|
await database.StringSetAsync(key, serializedValue, expiry);
|
||
|
}
|
||
|
|
||
|
public async Task<T?> GetCacheAsync<T>(string key)
|
||
|
{
|
||
|
var database = _connectionMultiplexer.GetDatabase();
|
||
|
var value = await database.StringGetAsync(key);
|
||
|
|
||
|
if (value.IsNullOrEmpty)
|
||
|
return default;
|
||
|
|
||
|
return JsonSerializer.Deserialize<T>(value);
|
||
|
}
|
||
|
}
|
||
|
}
|