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();
|
}
|
}
|
}
|