feat(WeightDeviceDataAlert): add functionality to check alerts by IDs and send notifications

This commit is contained in:
2026-01-15 20:06:43 +08:00
parent 6b29e702cf
commit cd2faeacbe
2 changed files with 63 additions and 0 deletions

View File

@@ -58,4 +58,11 @@ public class WeightDeviceDataAlertController {
this.service.checkAllAlertsAndNotify();
return true;
}
@PostMapping("/checkByIds")
@SysLog(action = "按ID检查告警规则并发送通知")
public Object checkByIds(@RequestBody IdRequest request) {
this.service.checkAlertsByIds(request.getIds());
return true;
}
}

View File

@@ -165,6 +165,62 @@ public class WeightDeviceDataAlertService
log.info("告警规则检查完成, 共检查 {} 条规则, 发送 {} 条通知", checkedCount, notifiedCount);
}
/**
* 检查指定ID列表的告警规则并发送通知
* @param alertIds 告警规则ID列表
*/
public void checkAlertsByIds(List<String> alertIds) {
if (alertIds == null || alertIds.isEmpty()) {
log.warn("告警规则ID列表为空");
return;
}
log.info("开始检查指定的 {} 条告警规则", alertIds.size());
// 查询指定ID的告警规则同时过滤掉已截止的规则
Specification<WeightDeviceDataAlertEntity> spec = (root, query, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();
// 过滤ID列表
predicates.add(root.get("id").in(alertIds));
// 过滤截止日期只查询未截止的规则endDate为null或endDate在当前时间之后
LocalDateTime now = LocalDateTime.now();
predicates.add(
criteriaBuilder.or(
criteriaBuilder.isNull(root.get("endDate")),
criteriaBuilder.greaterThan(root.get("endDate"), now)
)
);
return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
};
List<WeightDeviceDataAlertEntity> alerts = repository.findAll(spec);
if (alerts.isEmpty()) {
log.warn("没有找到有效的告警规则可能已截止或ID不存在");
return;
}
int checkedCount = 0;
int notifiedCount = 0;
for (WeightDeviceDataAlertEntity alert : alerts) {
try {
checkedCount++;
boolean notified = checkAndNotify(alert);
if (notified) {
notifiedCount++;
}
} catch (Exception e) {
log.error("检查告警规则失败, 规则ID: {}, 错误: {}", alert.getId(), e.getMessage(), e);
}
}
log.info("指定告警规则检查完成, 共检查 {} 条规则, 发送 {} 条通知", checkedCount, notifiedCount);
}
/**
* 检查单个告警规则并发送通知
* @param alert 告警规则