BotSharp/src/Infrastructure/BotSharp.Core/Infrastructures/RedisCacheService.cs

96 lines
2.1 KiB
C#
Raw Normal View History

2024-08-22 11:54:50 +00:00
using BotSharp.Abstraction.Infrastructures;
using Newtonsoft.Json;
using StackExchange.Redis;
namespace BotSharp.Core.Infrastructures;
2024-09-06 20:41:22 +00:00
public class RedisCacheService : ICacheService
2024-08-22 11:54:50 +00:00
{
private readonly BotSharpDatabaseSettings _settings;
private static ConnectionMultiplexer redis = null!;
2024-09-06 20:41:22 +00:00
public RedisCacheService(BotSharpDatabaseSettings settings)
2024-08-22 11:54:50 +00:00
{
_settings = settings;
}
public async Task<T?> GetAsync<T>(string key)
{
if (string.IsNullOrEmpty(_settings.Redis))
{
return default;
}
if (redis == null)
{
redis = ConnectionMultiplexer.Connect(_settings.Redis);
}
var db = redis.GetDatabase();
var value = await db.StringGetAsync(key);
if (value.HasValue)
{
return JsonConvert.DeserializeObject<T>(value);
}
return default;
}
public async Task<object> GetAsync(string key, Type type)
{
if (string.IsNullOrEmpty(_settings.Redis))
{
return default;
}
if (redis == null)
{
redis = ConnectionMultiplexer.Connect(_settings.Redis);
}
var db = redis.GetDatabase();
var value = await db.StringGetAsync(key);
if (value.HasValue)
{
return JsonConvert.DeserializeObject(value, type);
}
return default;
}
public async Task SetAsync<T>(string key, T value, TimeSpan? expiry)
{
if (string.IsNullOrEmpty(_settings.Redis))
{
return;
}
2024-09-06 20:41:22 +00:00
if (redis == null)
{
redis = ConnectionMultiplexer.Connect(_settings.Redis);
}
2024-08-22 11:54:50 +00:00
var db = redis.GetDatabase();
await db.StringSetAsync(key, JsonConvert.SerializeObject(value), expiry);
}
2024-09-26 22:22:06 +00:00
public async Task RemoveAsync(string key)
{
if (string.IsNullOrEmpty(_settings.Redis))
{
return;
}
if (redis == null)
{
redis = ConnectionMultiplexer.Connect(_settings.Redis);
}
var db = redis.GetDatabase();
await db.KeyDeleteAsync(key);
}
2024-08-22 11:54:50 +00:00
}