wanshenmean
2026-03-02 bfd4fd8e4a05a681ec10a47992294cf752a764c4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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);
                });
        }
    }
}