using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Options;
|
using WIDESEAWCS_RedisService.Connection;
|
using WIDESEAWCS_RedisService.Options;
|
|
namespace WIDESEAWCS_RedisService.Monitoring
|
{
|
public class RedisMonitorService : IRedisMonitorService
|
{
|
private readonly IRedisConnectionManager _connectionManager;
|
private readonly RedisOptions _options;
|
private readonly ILogger<RedisMonitorService> _logger;
|
|
public RedisMonitorService(
|
IRedisConnectionManager connectionManager,
|
IOptions<RedisOptions> options,
|
ILogger<RedisMonitorService> logger)
|
{
|
_connectionManager = connectionManager;
|
_options = options.Value;
|
_logger = logger;
|
}
|
|
public Dictionary<string, string> GetServerInfo()
|
{
|
var server = _connectionManager.GetServer();
|
var info = server.Info();
|
var result = new Dictionary<string, string>();
|
foreach (var group in info)
|
{
|
foreach (var item in group)
|
result[$"{group.Key}:{item.Key}"] = item.Value;
|
}
|
return result;
|
}
|
|
public RedisMemoryInfo GetMemoryInfo()
|
{
|
var server = _connectionManager.GetServer();
|
var info = server.Info("memory");
|
var memorySection = info.FirstOrDefault();
|
|
var memInfo = new RedisMemoryInfo();
|
if (memorySection == null) return memInfo;
|
|
var dict = memorySection.ToDictionary(x => x.Key, x => x.Value);
|
if (dict.TryGetValue("used_memory", out var used))
|
memInfo.UsedMemory = long.Parse(used);
|
if (dict.TryGetValue("used_memory_human", out var usedH))
|
memInfo.UsedMemoryHuman = usedH;
|
if (dict.TryGetValue("maxmemory", out var max))
|
memInfo.MaxMemory = long.Parse(max);
|
if (dict.TryGetValue("maxmemory_human", out var maxH))
|
memInfo.MaxMemoryHuman = maxH;
|
|
if (memInfo.MaxMemory > 0)
|
memInfo.UsagePercent = Math.Round((double)memInfo.UsedMemory / memInfo.MaxMemory * 100, 2);
|
|
return memInfo;
|
}
|
|
public bool HealthCheck()
|
{
|
try
|
{
|
var db = _connectionManager.GetDatabase();
|
var pong = db.Ping();
|
return pong.TotalMilliseconds < 5000;
|
}
|
catch (Exception ex)
|
{
|
_logger.LogError(ex, "Redis健康检查失败");
|
return false;
|
}
|
}
|
|
public long GetDbSize()
|
{
|
return _connectionManager.GetServer().DatabaseSize();
|
}
|
|
public long GetClientCount()
|
{
|
var info = _connectionManager.GetServer().Info("clients");
|
var section = info.FirstOrDefault();
|
if (section == null) return 0;
|
var dict = section.ToDictionary(x => x.Key, x => x.Value);
|
return dict.TryGetValue("connected_clients", out var count) ? long.Parse(count) : 0;
|
}
|
}
|
}
|