using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Options;
|
using StackExchange.Redis;
|
using WIDESEAWCS_RedisService.Connection;
|
using WIDESEAWCS_RedisService.Options;
|
|
namespace WIDESEAWCS_RedisService.Configuration
|
{
|
public class RedisConfigurationCenterService : IConfigurationCenterService
|
{
|
private readonly IRedisConnectionManager _connectionManager;
|
private readonly RedisOptions _options;
|
private readonly ILogger<RedisConfigurationCenterService> _logger;
|
|
public RedisConfigurationCenterService(
|
IRedisConnectionManager connectionManager,
|
IOptions<RedisOptions> options,
|
ILogger<RedisConfigurationCenterService> logger)
|
{
|
_connectionManager = connectionManager;
|
_options = options.Value;
|
_logger = logger;
|
}
|
|
private string BuildKey(string section) => $"{_options.KeyPrefix}config:{section}";
|
|
public bool Set(string section, string key, string value)
|
{
|
var db = _connectionManager.GetDatabase();
|
var result = db.HashSet(BuildKey(section), key, value);
|
// 发布变更通知
|
_connectionManager.GetSubscriber()
|
.Publish(RedisChannel.Literal($"{_options.KeyPrefix}config:change:{section}"), key);
|
return result;
|
}
|
|
public string? Get(string section, string key)
|
{
|
var val = _connectionManager.GetDatabase().HashGet(BuildKey(section), key);
|
return val.IsNullOrEmpty ? null : val.ToString();
|
}
|
|
public Dictionary<string, string> GetSection(string section)
|
{
|
var entries = _connectionManager.GetDatabase().HashGetAll(BuildKey(section));
|
return entries.ToDictionary(e => e.Name.ToString(), e => e.Value.ToString());
|
}
|
|
public bool Delete(string section, string key)
|
{
|
return _connectionManager.GetDatabase().HashDelete(BuildKey(section), key);
|
}
|
|
public void Subscribe(string section, Action<string, string> onChange)
|
{
|
_connectionManager.GetSubscriber()
|
.Subscribe(RedisChannel.Literal($"{_options.KeyPrefix}config:change:{section}"), (_, msg) =>
|
{
|
var changedKey = msg.ToString();
|
var value = Get(section, changedKey) ?? string.Empty;
|
onChange(changedKey, value);
|
});
|
}
|
}
|
}
|