wanshenmean
2026-03-04 17e5dbd7bd0364e27a33f1a7dab91cf33d5dcabc
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StackExchange.Redis;
using System.Linq;
using WIDESEAWCS_Core.Helper;
using WIDESEAWCS_RedisService.Options;
 
namespace WIDESEAWCS_RedisService.Connection
{
    public class RedisConnectionManager : IRedisConnectionManager
    {
        private readonly RedisOptions _options;
        private readonly ILogger<RedisConnectionManager> _logger;
        private readonly Lazy<ConnectionMultiplexer> _connection;
        private bool _disposed;
 
        public bool IsConnected
        {
            get
            {
                try
                {
                    // 强制访问Value来触发连接创建
                    var connected = _connection.Value.IsConnected;
                    return connected;
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, "IsConnected检查失败");
                    return false;
                }
            }
        }
 
        public RedisConnectionManager(IOptions<RedisOptions> options, ILogger<RedisConnectionManager> logger)
        {
            _options = options.Value;
            _logger = logger;
            _connection = new Lazy<ConnectionMultiplexer>(CreateConnection);
        }
 
        private ConnectionMultiplexer CreateConnection()
        {
            try
            {
                var configOptions = ConfigurationOptions.Parse(_options.ConnectionString);
                configOptions.AbortOnConnectFail = false;
                configOptions.ConnectRetry = _options.ConnectRetry;
                configOptions.DefaultDatabase = _options.DefaultDatabase;
 
                if (_options.EnableSentinel && _options.SentinelEndpoints.Count > 0)
                {
                    configOptions.ServiceName = _options.SentinelMasterName;
                    foreach (var endpoint in _options.SentinelEndpoints)
                    {
                        configOptions.EndPoints.Add(endpoint);
                    }
                }
 
                var connection = ConnectionMultiplexer.Connect(configOptions);
                connection.ConnectionFailed += (_, e) =>
                    ConsoleHelper.WriteErrorLine($"Redis连接失败: {e.FailureType}");
                connection.ConnectionRestored += (_, e) =>
                    ConsoleHelper.WriteSuccessLine($"Redis连接恢复: {e.EndPoint}");
 
                ConsoleHelper.WriteSuccessLine($"Redis连接成功: {string.Join(",", configOptions.EndPoints)}");
                return connection;
            }
            catch (Exception ex)
            {
                ConsoleHelper.WriteErrorLine($"Redis连接创建失败:{ex.Message}");
                throw;
            }
        }
 
        public IDatabase GetDatabase(int db = -1)
        {
            return _connection.Value.GetDatabase(db == -1 ? _options.DefaultDatabase : db);
        }
 
        public IServer GetServer()
        {
            var endpoints = _connection.Value.GetEndPoints();
            return _connection.Value.GetServer(endpoints[0]);
        }
 
        public ISubscriber GetSubscriber()
        {
            return _connection.Value.GetSubscriber();
        }
 
        public ConnectionMultiplexer GetConnection()
        {
            return _connection.Value;
        }
 
        public void Dispose()
        {
            if (_disposed) return;
            _disposed = true;
            if (_connection.IsValueCreated)
                _connection.Value.Dispose();
        }
    }
}