搭建消息告警模块以及跨网推送服务,支持企微,飞书,钉钉通知

This commit is contained in:
2026-09-03 14:02:35 +08:00
parent cfa8e78d33
commit 3927b0c201
40 changed files with 4360 additions and 7 deletions
+34 -1
View File
@@ -1,5 +1,7 @@
using Model.Dto.Inspection;
using Model.Entity.Inspection;
using ORM;
using Service.Interface;
namespace WebAPI.Services
{
@@ -22,9 +24,11 @@ namespace WebAPI.Services
}
private readonly Dictionary<string, BoxState> _states = new();
private readonly IServiceScopeFactory _scopeFactory;
public TemperatureBoxSimulator()
public TemperatureBoxSimulator(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
for (int i = 1; i <= DeviceCount; i++)
{
_states[$"BOX-{i:D3}"] = new BoxState();
@@ -39,6 +43,7 @@ namespace WebAPI.Services
{
var now = DateTime.Now;
var batch = new List<TemperatureBoxDataEntity>(DeviceCount);
var alarmDevices = new List<(string Code, double Temp)>();
foreach (var kv in _states)
{
@@ -48,6 +53,10 @@ namespace WebAPI.Services
s.Humidity = Math.Clamp(s.Humidity + (Rnd.NextDouble() - 0.5) * 3, 20, 90);
bool alarm = s.Temperature >= AlarmTemp;
if (alarm)
{
alarmDevices.Add((kv.Key, Math.Round(s.Temperature, 1)));
}
batch.Add(new TemperatureBoxDataEntity
{
DeviceCode = kv.Key,
@@ -62,6 +71,30 @@ namespace WebAPI.Services
// 批量插入
await SqlSugarContext.DbContext.Insertable(batch).ExecuteCommandAsync();
// 报警设备上报告警中心(告警中心内部有 5 分钟合并窗口,不会每秒重复建告警)
if (alarmDevices.Count > 0)
{
// 单例 HostedService 不能直接注入 Scoped 服务,按批次创建作用域解析
using var scope = _scopeFactory.CreateScope();
var alertCenter = scope.ServiceProvider.GetRequiredService<IAlertCenterService>();
foreach (var (code, temp) in alarmDevices)
{
await alertCenter.RaiseAsync(new AlertRaiseDto
{
Source = AlertSourceEnum.Collection,
DeviceCode = code,
DeviceName = $"温度箱 {code}",
DeviceType = "TemperatureBox",
Metric = "Temperature",
AlertType = AlertTypeEnum.ThresholdExceed,
AlertLevel = AlertLevelEnum.Urgent,
CurrentValue = temp,
ThresholdValue = AlarmTemp,
Content = $"温度箱 {code} 温度超限:当前 {temp}℃ ≥ 报警阈值 {AlarmTemp}℃"
});
}
}
}
catch (Exception ex)
{