Catalogger.NET/Catalogger.Backend/Database/Redis/RedisService.cs

24 lines
763 B
C#
Raw Normal View History

using System.Text.Json;
using Humanizer;
using StackExchange.Redis;
namespace Catalogger.Backend.Database.Redis;
public class RedisService(Config config)
{
private readonly ConnectionMultiplexer _multiplexer = ConnectionMultiplexer.Connect(config.Database.Redis!);
public IDatabase GetDatabase(int db = -1) => _multiplexer.GetDatabase(db);
public async Task SetAsync<T>(string key, T value, TimeSpan? expiry = null)
{
var json = JsonSerializer.Serialize(value);
await GetDatabase().StringSetAsync(key, json, expiry);
}
public async Task<T?> GetAsync<T>(string key)
{
var value = await GetDatabase().StringGetAsync(key);
return value.IsNull ? default : JsonSerializer.Deserialize<T>(value!);
}
}