| | |
| | | using Microsoft.Extensions.Options; |
| | | using StackExchange.Redis; |
| | | using System.Linq; |
| | | using WIDESEAWCS_Core.Helper; |
| | | using WIDESEAWCS_RedisService.Options; |
| | | |
| | | namespace WIDESEAWCS_RedisService.Connection |
| | |
| | | { |
| | | // 强制访问Value来触发连接创建 |
| | | var connected = _connection.Value.IsConnected; |
| | | _logger.LogDebug("IsConnected检查: IsValueCreated={IsValueCreated}, IsConnected={Connected}", |
| | | _connection.IsValueCreated, connected); |
| | | return connected; |
| | | } |
| | | catch (Exception ex) |
| | |
| | | { |
| | | _options = options.Value; |
| | | _logger = logger; |
| | | _logger.LogInformation("RedisConnectionManager构造开始, ConnectionString={ConnectionString}, Enabled={Enabled}", |
| | | _options.ConnectionString, _options.Enabled); |
| | | _connection = new Lazy<ConnectionMultiplexer>(CreateConnection); |
| | | _logger.LogInformation("RedisConnectionManager构造完成, Lazy已创建"); |
| | | } |
| | | |
| | | private ConnectionMultiplexer CreateConnection() |
| | | { |
| | | try |
| | | { |
| | | _logger.LogInformation("开始创建Redis连接, ConnectionString={ConnectionString}", _options.ConnectionString); |
| | | var configOptions = ConfigurationOptions.Parse(_options.ConnectionString); |
| | | configOptions.AbortOnConnectFail = false; |
| | | configOptions.ConnectRetry = _options.ConnectRetry; |
| | | configOptions.DefaultDatabase = _options.DefaultDatabase; |
| | | _logger.LogInformation("ConfigurationOptions解析完成, EndPoints={EndPoints}", string.Join(",", configOptions.EndPoints.Select(e => e.ToString()))); |
| | | |
| | | if (_options.EnableSentinel && _options.SentinelEndpoints.Count > 0) |
| | | { |
| | |
| | | |
| | | var connection = ConnectionMultiplexer.Connect(configOptions); |
| | | connection.ConnectionFailed += (_, e) => |
| | | _logger.LogError("Redis连接失败: {FailureType}", e.FailureType); |
| | | ConsoleHelper.WriteErrorLine($"Redis连接失败: {e.FailureType}"); |
| | | connection.ConnectionRestored += (_, e) => |
| | | _logger.LogInformation("Redis连接恢复: {EndPoint}", e.EndPoint); |
| | | ConsoleHelper.WriteSuccessLine($"Redis连接恢复: {e.EndPoint}"); |
| | | |
| | | _logger.LogInformation("Redis连接成功: {EndPoints}", string.Join(",", configOptions.EndPoints)); |
| | | ConsoleHelper.WriteSuccessLine($"Redis连接成功: {string.Join(",", configOptions.EndPoints)}"); |
| | | return connection; |
| | | } |
| | | catch (Exception ex) |
| | | { |
| | | _logger.LogError(ex, "Redis连接创建失败"); |
| | | ConsoleHelper.WriteErrorLine($"Redis连接创建失败:{ex.Message}"); |
| | | throw; |
| | | } |
| | | } |