feat: 添加Npgsql包支持,更新Redis连接配置,增加Kafka心跳检查功能,完善Postgres配置,新增发布配置文件

This commit is contained in:
2026-02-09 19:31:55 +08:00
parent 4d37bf5a09
commit 7a60c62166
6 changed files with 160 additions and 5 deletions

View File

@@ -9,6 +9,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="CSRedisCore" Version="3.8.806" /> <PackageReference Include="CSRedisCore" Version="3.8.806" />
<PackageReference Include="NLog" Version="6.0.4" /> <PackageReference Include="NLog" Version="6.0.4" />
<PackageReference Include="Npgsql" Version="8.0.5" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -17,14 +17,14 @@ namespace Common
public static CSRedisClient? redis1; public static CSRedisClient? redis1;
private const string ip = "127.0.0.1"; private const string ip = "127.0.0.1";
private const string port = "6379"; private const string port = "10079";//10079
static CSRedisCacheHelper() static CSRedisCacheHelper()
{ {
var redisHostStr = string.Format("{0}:{1}", ip, port); var redisHostStr = string.Format("{0}:{1}", ip, port);
if (!string.IsNullOrEmpty(redisHostStr)) if (!string.IsNullOrEmpty(redisHostStr))
{ {
redis = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=0"); redis = new CSRedisClient(redisHostStr + ",password=blw@redis-ser@123,defaultDatabase=0");
redis1 = new CSRedisClient(redisHostStr + ",password=,defaultDatabase=1"); redis1 = new CSRedisClient(redisHostStr + ",password=blw@redis-ser@123,defaultDatabase=1");
var DingYueMsg = ("CallServer", new Action<SubscribeMessageEventArgs>(async (args) => var DingYueMsg = ("CallServer", new Action<SubscribeMessageEventArgs>(async (args) =>
{ {
string body = args.Body; string body = args.Body;

View File

@@ -3,6 +3,8 @@ using Common;
using System.Threading; using System.Threading;
using NLog; using NLog;
using System.Diagnostics; using System.Diagnostics;
using Npgsql;
using Microsoft.Extensions.Configuration;
namespace AutoNotificatPhone.Models namespace AutoNotificatPhone.Models
{ {
@@ -17,6 +19,12 @@ namespace AutoNotificatPhone.Models
private Dictionary<DateTime, bool> _executedTasks = []; private Dictionary<DateTime, bool> _executedTasks = [];
// 消息控制器实例 // 消息控制器实例
private readonly CallAndMsgController _callAndMsgController = new(); private readonly CallAndMsgController _callAndMsgController = new();
private readonly IConfiguration _configuration;
public TimerClass(IConfiguration configuration)
{
_configuration = configuration;
}
/// <summary> /// <summary>
/// 后台服务主执行方法 /// 后台服务主执行方法
@@ -48,6 +56,7 @@ namespace AutoNotificatPhone.Models
await CheckRcuOnlineAsync(); await CheckRcuOnlineAsync();
await CheckTotalSendPackageAsync(); await CheckTotalSendPackageAsync();
await CheckTotalRecvPackageAsync(); await CheckTotalRecvPackageAsync();
await CheckKafkaHeartbeatAsync();
} }
catch (TaskCanceledException) catch (TaskCanceledException)
{ {
@@ -262,7 +271,7 @@ namespace AutoNotificatPhone.Models
//logger.Error($"RCU服务器的CPU使用率-AVG:{cpuAvg},MAX:{cpuMax}"); //logger.Error($"RCU服务器的CPU使用率-AVG:{cpuAvg},MAX:{cpuMax}");
// 检查是否超过阈值 // 检查是否超过阈值
if (CheckThreshold(cpuAvgValues, 70, 6))//(CheckThreshold(cpuMaxValues, 90, 6) || CheckThreshold(cpuAvgValues, 85, 6)) if (CheckThreshold(cpuAvgValues, 80, 6))//(CheckThreshold(cpuMaxValues, 90, 6) || CheckThreshold(cpuAvgValues, 85, 6))
{ {
// 触发CPU警报 // 触发CPU警报
ExecuteCpuAlert(cpuMaxValues, ParseCpuValues(CSRedisCacheHelper.redis1.Get<string>("UDPPackage_CPUMin")), cpuAvgValues); ExecuteCpuAlert(cpuMaxValues, ParseCpuValues(CSRedisCacheHelper.redis1.Get<string>("UDPPackage_CPUMin")), cpuAvgValues);
@@ -419,6 +428,115 @@ namespace AutoNotificatPhone.Models
); );
} }
/// <summary>
/// 检查Kafka入库心跳PostgreSQL
/// </summary>
private async Task CheckKafkaHeartbeatAsync()
{
try
{
string? connectionString = BuildPostgresConnectionString();
if (string.IsNullOrWhiteSpace(connectionString))
{
logger.Error("Postgres配置缺失无法检查Kafka入库心跳");
return;
}
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync();
const string sql = "select ts_ms from heartbeat.heartbeat_events order by ts_ms desc limit 1";
await using var command = new NpgsqlCommand(sql, connection);
object? result = await command.ExecuteScalarAsync();
if (result == null || result == DBNull.Value)
{
ExecuteKafkaInactiveAlert();
return;
}
if (!long.TryParse(result.ToString(), out long lastTsMs))
{
logger.Error("Kafka入库心跳ts_ms解析失败");
return;
}
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
if (nowMs - lastTsMs > TimeSpan.FromMinutes(5).TotalMilliseconds)
{
ExecuteKafkaInactiveAlert();
}
}
catch (Exception ex)
{
logger.Error($"Kafka入库心跳检查错误: {ex.Message}");
}
await Task.CompletedTask;
}
/// <summary>
/// 生成PostgreSQL连接字符串
/// </summary>
private string? BuildPostgresConnectionString()
{
IConfigurationSection section = _configuration.GetSection("Postgres");
string? host = section["Host"];
string? portString = section["Port"];
string? database = section["Database"];
string? username = section["User"];
string? password = section["Password"];
string? maxConnectionsString = section["MaxConnections"];
string? idleTimeoutMsString = section["IdleTimeoutMs"];
if (string.IsNullOrWhiteSpace(host) ||
string.IsNullOrWhiteSpace(portString) ||
string.IsNullOrWhiteSpace(database) ||
string.IsNullOrWhiteSpace(username) ||
string.IsNullOrWhiteSpace(password))
{
return null;
}
if (!int.TryParse(portString, out int port))
{
return null;
}
var builder = new NpgsqlConnectionStringBuilder
{
Host = host,
Port = port,
Database = database,
Username = username,
Password = password
};
if (int.TryParse(maxConnectionsString, out int maxConnections) && maxConnections > 0)
{
builder.MaxPoolSize = maxConnections;
}
if (int.TryParse(idleTimeoutMsString, out int idleTimeoutMs) && idleTimeoutMs > 0)
{
builder.ConnectionIdleLifetime = Math.Max(1, idleTimeoutMs / 1000);
}
return builder.ConnectionString;
}
/// <summary>
/// 执行Kafka入库失活警报
/// </summary>
private void ExecuteKafkaInactiveAlert()
{
SendAlert(
smsContent: "[BLV运维提示] BLS数据库5分钟内入库数据为0。",
callContent: "BLV运维提示 BLS数据库5分钟内入库数据为0",
alertType: "BLS-数据库入库警报",
extendedDeadline: true
);
}
/// <summary> /// <summary>
/// 解析CPU值字符串为整数列表 /// 解析CPU值字符串为整数列表
/// </summary> /// </summary>

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- https://go.microsoft.com/fwlink/?LinkID=208121. -->
<Project>
<PropertyGroup>
<DeleteExistingFiles>true</DeleteExistingFiles>
<ExcludeApp_Data>false</ExcludeApp_Data>
<LaunchSiteAfterPublish>true</LaunchSiteAfterPublish>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>bin\Release\net8.0\publish\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<SiteUrlToLaunchAfterPublish />
<TargetFramework>net8.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<ProjectGuid>40394cc0-be9d-457f-b0e8-115fcfbaaf85</ProjectGuid>
<SelfContained>false</SelfContained>
</PropertyGroup>
</Project>

View File

@@ -5,5 +5,14 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"AllowedHosts": "*" "AllowedHosts": "*",
"Postgres": {
"Host": "10.8.8.109",
"Port": "5433",
"Database": "log_platform",
"User": "log_admin",
"Password": "YourActualStrongPasswordForPostgres!",
"MaxConnections": "2",
"IdleTimeoutMs": "30000"
}
} }

7
config.md Normal file
View File

@@ -0,0 +1,7 @@
POSTGRES_HOST=10.8.8.109
POSTGRES_PORT=5433
POSTGRES_DATABASE=log_platform
POSTGRES_USER=log_admin
POSTGRES_PASSWORD=YourActualStrongPasswordForPostgres!
POSTGRES_MAX_CONNECTIONS=2
POSTGRES_IDLE_TIMEOUT_MS=30000