fix(通知): 聚合去重键从小时桶改自然日,刷新不再把已读点亮回未读

后台「通知」被刷屏的两个乘数:一条告警一天最多重发 24 次(小时桶换键),
以及刷新时 set read_at=null 把用户已读过的红点重新点亮。现在 task_failed /
service_down / maixiang_anomaly 五类键统一按「用户×模块×自然日」聚合,
pushOrRefresh 只更新文案不动 read_at;桶的日期取事件自身的 updatedAt,
跨零点轮询不会把昨天的失败挪进今天的桶。
This commit is contained in:
2026-10-02 10:35:06 +08:00
parent b5614c9f10
commit 0fd0ee17ee
8 changed files with 178 additions and 48 deletions
@@ -14,7 +14,7 @@ public class NotificationProperties {
/** 扫描总开关:关闭后任务失败扫描与服务探测都不执行(应急降噪)。 */
private boolean scanEnabled = true;
/** 扫描间隔(毫秒),默认 5 分钟(任务失败聚合按小时去重,高频扫描不会重复提醒)。 */
/** 扫描间隔(毫秒),默认 5 分钟(聚合通知按自然日去重,高频扫描只会刷新同一条、不会重复提醒)。 */
private long scanIntervalMs = 5 * 60 * 1000L;
/** 首次执行延迟(毫秒),默认 2 分钟,避开启动阶段的数据库压力。 */
@@ -41,9 +41,9 @@ import java.util.stream.Collectors;
* "采集机掉线"(2026-09-29 停摆 6 小时即如此,且当时 210 条 pending 没到 300 的阈值,
* 连积压检查都没触发)。
*
* <p>全部为管理员全局事件(与「服务探测」一致,不按数据权限过滤);去重键:
* 停滞类按天、失败/积压按小时、空结果按任务——同一异常窗口内只提醒一次,
* 情况变化(新增停滞任务/失败数增长)时刷新内容并重新提醒。
* <p>全部为管理员全局事件(与「服务探测」一致,不按数据权限过滤);去重键按自然日
* (空结果按任务):同一异常当天只一条,情况变化(新增停滞任务/失败数增长)时刷新内容,
* 但不把已读的重新点亮 —— 一台掉线的采集机会被扫几十轮,逐轮点亮等于刷屏。
*
* <p>由 {@link NotificationScanScheduler} 在分布式锁内调用;单项检查异常只记日志不中断其余检查。
*/
@@ -66,7 +66,6 @@ public class MaixiangAnomalyScanner {
private static final int REASON_MAX_LENGTH = 120;
private static final DateTimeFormatter DAY_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
private static final DateTimeFormatter HOUR_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHH");
private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/** 麦象任务类型 → 中文名(未登记的类型回退原始值)。 */
@@ -146,7 +145,7 @@ public class MaixiangAnomalyScanner {
String content = "麦象采集机疑似掉线:所有打点信号已静默 " + (machineIdle / 60) + " 分钟(" + detail
+ ")。该机器无开机自启,重启/升配后必须人工拉起;请检查 5 个 worker 是否在运行"
+ "(start_task.bat 或 更新并重启.bat)。";
push(audience, "采集机掉线", content, "maixiang_silent:" + now.format(HOUR_FORMAT));
push(audience, "采集机掉线", content, "maixiang_silent:" + now.format(DAY_FORMAT));
}
/** 打点信号的中文标签:接口没给 label 时回退信号名。 */
@@ -214,7 +213,7 @@ public class MaixiangAnomalyScanner {
push(audience, "麦象任务滞留未消费", content, "maixiang_stuck_single:" + now.format(DAY_FORMAT));
}
/** 任务失败:近窗口内 status=3 的单任务达到最小条数(按小时桶聚合,原因取最新一条)。 */
/** 任务失败:近窗口内 status=3 的单任务达到最小条数(按自然日聚合,原因取最新一条)。 */
void checkFailedSingleTasks(NotificationDispatchService.AdminAudience audience, LocalDateTime now) {
SingleTaskPage page = consoleClient.singleTasks(3, null, FAIL_PAGE_SIZE);
LocalDateTime windowStart = now.minusMinutes(FAIL_WINDOW_MINUTES);
@@ -234,7 +233,7 @@ public class MaixiangAnomalyScanner {
+ typeSummary(failed.stream().map(SingleTaskItem::taskType).toList()) + ")"
+ (reason.isEmpty() ? "" : ";最近失败原因:" + reason)
+ "。请排查采集端配置(如代理余额、任务类型注册)。";
push(audience, "麦象任务失败", content, "maixiang_fail:" + now.format(HOUR_FORMAT));
push(audience, "麦象任务失败", content, "maixiang_fail:" + now.format(DAY_FORMAT));
}
/** 批量任务空结果:最近完成但结果 0 条(worker 报错时批次仍会被标为"已完成")。 */
@@ -289,7 +288,7 @@ public class MaixiangAnomalyScanner {
}
String content = "麦象单任务队列积压:" + detail + "(阈值 待处理 " + pendingThreshold
+ " 且无消费 / 处理中 " + processingThreshold + ")。消费端可能掉线,请尽快排查采集机 worker。";
push(audience, "麦象队列积压", content, "maixiang_queue_backlog:" + now.format(HOUR_FORMAT));
push(audience, "麦象队列积压", content, "maixiang_queue_backlog:" + now.format(DAY_FORMAT));
}
// ======================== 文案辅助 ========================
@@ -29,11 +29,11 @@ import java.util.Map;
* 站内通知扫描:任务失败聚合提醒 + 下游服务健康探测。
*
* <p>任务失败:回看窗口内进入失败终态的任务(biz_file_task / brand_crawl_tasks),
* 按「用户 × 模块 × 小时」聚合,同一小时桶内增量刷新同一条通知(不刷屏);
* 按「用户 × 模块 × 自然日」聚合,同一天内增量刷新同一条通知(不刷屏);
* 用户侧推给任务创建者,管理员侧按数据权限推给管辖该用户的管理员。
*
* <p>服务探测:品牌检测服务(15126) / 跟价任务 API(18960) / jikip 代理接口,
* 失败立即重试一次(过滤瞬抖),两次都失败才告警;同服务每小时最多一条。
* 失败立即重试一次(过滤瞬抖),两次都失败才告警;同服务每天最多一条。
*
* <p>麦象异常扫描:见 {@link MaixiangAnomalyScanner}(批量/单任务停滞、任务失败、
* 批量任务空结果、队列积压 → 管理员通知),与任务失败扫描共用本调度与分布式锁。
@@ -55,7 +55,7 @@ public class NotificationScanScheduler {
private static final int REASON_MAX_LENGTH = 120;
private static final int PROBE_READ_TIMEOUT_MILLIS = 8_000;
private static final DateTimeFormatter HOUR_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHH");
private static final DateTimeFormatter DAY_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
/**
* 任务模块类型 → 中文名:直接取模块注册表(G6),新增模块只需在
@@ -102,7 +102,7 @@ public class NotificationScanScheduler {
}
}
/** 任务失败聚合扫描:窗口内失败终态任务按「用户 × 模块 × 小时」聚合成一条通知。 */
/** 任务失败聚合扫描:窗口内失败终态任务按「用户 × 模块 × 自然日」聚合成一条通知。 */
void scanFailedTasks() {
LocalDateTime cutoff = LocalDateTime.now()
.minusMinutes(Math.max(1, properties.getTaskFailedWindowMinutes()));
@@ -121,7 +121,7 @@ public class NotificationScanScheduler {
continue;
}
failed.add(new FailedTask(task.getId(), displayTaskNo(task.getTaskNo(), task.getId()),
task.getModuleType(), task.getUserId(), task.getErrorMessage()));
task.getModuleType(), task.getUserId(), task.getErrorMessage(), task.getUpdatedAt()));
}
List<BrandCrawlTaskEntity> brandTasks = brandCrawlTaskMapper.selectList(new LambdaQueryWrapper<BrandCrawlTaskEntity>()
.select(BrandCrawlTaskEntity::getId, BrandCrawlTaskEntity::getUserId,
@@ -135,19 +135,18 @@ public class NotificationScanScheduler {
continue;
}
failed.add(new FailedTask(task.getId(), "#" + task.getId(),
BRAND_MODULE_TYPE, task.getUserId(), task.getErrorMessage()));
BRAND_MODULE_TYPE, task.getUserId(), task.getErrorMessage(), task.getUpdatedAt()));
}
if (failed.isEmpty()) {
log.info("[notification-scan] 近 {} 分钟无失败任务", properties.getTaskFailedWindowMinutes());
return;
}
String hour = LocalDateTime.now().format(HOUR_FORMAT);
Map<BucketKey, List<FailedTask>> buckets = new LinkedHashMap<>();
for (FailedTask task : failed) {
String moduleType = normalizeModuleType(task.moduleType());
buckets.computeIfAbsent(new BucketKey(task.userId(), moduleType, hour), key -> new ArrayList<>())
.add(task);
buckets.computeIfAbsent(new BucketKey(task.userId(), moduleType, dayOf(task.updatedAt())),
key -> new ArrayList<>()).add(task);
}
NotificationDispatchService.AdminAudience audience = notificationDispatchService.prepareAdminAudience();
@@ -179,7 +178,7 @@ public class NotificationScanScheduler {
adminPushed += notificationDispatchService.pushToAdmins(audience,
NotificationService.SCENE_TASK_FAILED, NotificationService.LEVEL_WARNING,
"用户任务失败:" + username, adminContent,
"task_failed_admin:" + key.userId() + ":" + key.moduleType() + ":" + key.hour(),
"task_failed_admin:" + key.userId() + ":" + key.moduleType() + ":" + key.day(),
key.userId());
}
log.info("[notification-scan] 任务失败扫描完成 窗口={}分钟 失败任务={} 聚合桶={} 用户通知={} 管理员通知={}",
@@ -255,7 +254,7 @@ public class NotificationScanScheduler {
}
}
/** 探测结果上报:正常记 info;故障按小时去重推管理员通知;outcome=null 表示跳过。 */
/** 探测结果上报:正常记 info;故障按自然日去重推管理员通知;outcome=null 表示跳过。 */
private void reportProbe(String serviceKey, String serviceLabel, ProbeOutcome outcome) {
if (outcome == null) {
return;
@@ -265,12 +264,11 @@ public class NotificationScanScheduler {
return;
}
log.warn("[notification-scan] 服务探测失败 service={} detail={}", serviceLabel, outcome.detail());
String hour = LocalDateTime.now().format(HOUR_FORMAT);
notificationDispatchService.pushToAdmins(NotificationService.SCENE_SERVICE_DOWN,
NotificationService.LEVEL_ERROR,
serviceLabel + "不可用",
serviceLabel + "探测失败:" + outcome.detail() + "。该服务相关任务可能大面积失败,请尽快排查。",
"service_down:" + serviceKey + ":" + hour, null);
"service_down:" + serviceKey + ":" + dayOf(LocalDateTime.now()), null);
}
/** 通知保留期清理:每天最多一次;已读与未读各按自己的保留天数。 */
@@ -287,7 +285,12 @@ public class NotificationScanScheduler {
}
private String dedupeKeyOf(BucketKey key) {
return "task_failed:" + key.userId() + ":" + key.moduleType() + ":" + key.hour();
return "task_failed:" + key.userId() + ":" + key.moduleType() + ":" + key.day();
}
/** 聚合桶的日期标签:取事件自身所属自然日,跨零点轮询时不会把昨天的失败挪进今天的桶。 */
private String dayOf(LocalDateTime at) {
return (at == null ? LocalDateTime.now() : at).format(DAY_FORMAT);
}
private String taskNoPreview(List<FailedTask> tasks) {
@@ -355,12 +358,13 @@ public class NotificationScanScheduler {
return current.getClass().getSimpleName() + ": " + message;
}
/** 聚合桶键:用户 × 模块 × 小时。 */
record BucketKey(Long userId, String moduleType, String hour) {
/** 聚合桶键:用户 × 模块 × 自然日。 */
record BucketKey(Long userId, String moduleType, String day) {
}
/** 统一视图的失败任务(两类表归一)。 */
record FailedTask(Long id, String taskNo, String moduleType, Long userId, String errorMessage) {
/** 统一视图的失败任务(两类表归一);updatedAt 即失败终态时间,决定落入哪一天的桶。 */
record FailedTask(Long id, String taskNo, String moduleType, Long userId, String errorMessage,
LocalDateTime updatedAt) {
}
/** 探测结果。 */
@@ -107,10 +107,11 @@ public class NotificationService {
}
/**
* 同键推送或刷新:不存在则新建;已存在且内容有变化时更新内容并重置为未读
* (用于小时桶聚合的增量更新:同小时内新增失败任务时刷新计数与明细)。
* 同键推送或刷新:不存在则新建;已存在且内容有变化时只更新文案,
* <b>不动 read_at</b>(聚合通知的去重键按自然日,同一条一天内会被刷新很多次,
* 重新点亮已读等于把红点做成闹钟)。
*
* @return true=新建或内容有更新(用户有新信息),false=无变化或去重未命中变化
* @return true=新建或内容有更新,false=无变化
*/
public boolean pushOrRefresh(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey) {
@@ -131,8 +132,7 @@ public class NotificationService {
.eq(UserNotificationEntity::getId, existing.getId())
.set(UserNotificationEntity::getTitle, nextTitle)
.set(UserNotificationEntity::getContent, nextContent)
.set(UserNotificationEntity::getLevel, normalize(level).isEmpty() ? LEVEL_WARNING : level)
.set(UserNotificationEntity::getReadAt, null));
.set(UserNotificationEntity::getLevel, normalize(level).isEmpty() ? LEVEL_WARNING : level));
log.info("[notification] 同键通知已刷新 id={} userId={} scene={} dedupeKey={}",
existing.getId(), userId, scene, key);
return true;