perf(syslog): 统计异步化并按采样保留率自适应调整业务批量
- 入口统计改用独立 Kafka 消费组,移除主消费同步统计写库 - DIRECT 模式入库计数改为事务提交后异步投递,取消事实事务内统计 Outbox 写入 - 采样审计、告警分钟桶通知改为后台处理,异常不阻断主消费或回滚告警 - RAW 基础业务批量默认 500,按保留率动态扩大,上限 3000 - 限制业务块字节数及规则任务数量,保留告警全量处理和整次 poll 完成后提交 - 细化 SLOW_SYSLOG_BATCH,补充批次关联、线程排队、数据库执行及提交耗时 - 更新 v4 升级说明,明确异步统计损失风险及现场验证方法 验证:JDK 8 构建成功,232 项测试通过。 升级:复用现有表和 Kafka Topic,无新增建表或建 Topic 脚本要求。
This commit is contained in:
+32
-15
@@ -12,7 +12,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** 先提交小时审计,再允许调用方执行有损采样;审计失败时调用方必须回退全量保留。 */
|
||||
/** 消费优先:小时采样审计后台尽力保存,失败不改变采样决策,不等待主消费。 */
|
||||
@Slf4j
|
||||
@Service
|
||||
public class BacklogSamplingAuditService {
|
||||
@@ -21,6 +21,11 @@ public class BacklogSamplingAuditService {
|
||||
private final BacklogSamplingMetrics metrics;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private volatile long retryAfterMs;
|
||||
private final BestEffortAuxiliaryQueue queue = new BestEffortAuxiliaryQueue("SAMPLING_AUDIT", 256, 50000, false);
|
||||
|
||||
@javax.annotation.PostConstruct public void start() { queue.start(); }
|
||||
@javax.annotation.PreDestroy public void stop() { queue.stop(); }
|
||||
public Map<String, Object> status() { return queue.status(); }
|
||||
|
||||
public BacklogSamplingAuditService(BacklogRetentionAuditMapper mapper,
|
||||
BacklogSamplingProperties properties,
|
||||
@@ -32,34 +37,46 @@ public class BacklogSamplingAuditService {
|
||||
this.transactionManager = transactionManager;
|
||||
}
|
||||
|
||||
/** 返回 false 表示不能安全采样,调用方应保留当前批次全部数据。 */
|
||||
public boolean recordBeforeDropping(List<BacklogRetentionDelta> deltas) {
|
||||
/** 返回值仅代表入队是否成功,不影响调用方原采样决策。 */
|
||||
public boolean recordAsync(List<BacklogRetentionDelta> deltas) {
|
||||
if (deltas == null || deltas.isEmpty()) return true;
|
||||
long affectedMessages = messageCount(deltas);
|
||||
long now = System.currentTimeMillis();
|
||||
if (now < retryAfterMs) {
|
||||
metrics.auditFailure(affectedMessages);
|
||||
long affectedMessages = 0L;
|
||||
try {
|
||||
affectedMessages = messageCount(deltas);
|
||||
final long taskMessages = affectedMessages;
|
||||
List<BacklogRetentionDelta> aggregated = aggregate(deltas);
|
||||
metrics.record(aggregated); // 决策指标,不再假称这些数字已写入审计数据库。
|
||||
if (System.currentTimeMillis() < retryAfterMs) {
|
||||
queue.loss("DATABASE_BACKOFF", null);
|
||||
metrics.auditLoss(affectedMessages);
|
||||
return false;
|
||||
}
|
||||
boolean offered = queue.offer(aggregated.size(), () -> writeAudit(aggregated, taskMessages));
|
||||
if (!offered) metrics.auditLoss(affectedMessages);
|
||||
return offered;
|
||||
} catch (RuntimeException failure) {
|
||||
queue.loss("PREPARE_FAILED", failure);
|
||||
metrics.auditLoss(affectedMessages);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
List<BacklogRetentionDelta> aggregated = aggregate(deltas);
|
||||
private void writeAudit(List<BacklogRetentionDelta> aggregated, long affectedMessages) {
|
||||
try {
|
||||
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
|
||||
transaction.setPropagationBehavior(org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
transaction.setTimeout(Math.max(1, properties.getAuditTimeoutSeconds()));
|
||||
transaction.execute(status -> {
|
||||
for (BacklogRetentionDelta delta : aggregated) mapper.upsert(delta);
|
||||
return null;
|
||||
});
|
||||
retryAfterMs = 0L;
|
||||
metrics.record(aggregated);
|
||||
return true;
|
||||
} catch (RuntimeException failure) {
|
||||
retryAfterMs = System.currentTimeMillis() + Math.max(1L, properties.getAuditRetryBackoffMs());
|
||||
metrics.auditFailure(affectedMessages);
|
||||
log.error("[BACKLOG_SAMPLING_AUDIT_FAILURE] 小时采样审计写入失败,当前批次自动回退全量保留: "
|
||||
+ "messages={}, groups={}, retryBackoffMs={}",
|
||||
affectedMessages, aggregated.size(), properties.getAuditRetryBackoffMs(), failure);
|
||||
return false;
|
||||
queue.pause(properties.getAuditRetryBackoffMs());
|
||||
metrics.auditWriteFailed(affectedMessages);
|
||||
// 审计为累加UPSERT;提交结果不确定时自动重放可能双计数,当前选择记录损失而不重放。
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+6
@@ -20,6 +20,10 @@ public class BacklogSamplingMetrics {
|
||||
private final LongAdder rawDropped = new LongAdder();
|
||||
private final LongAdder auditWriteFailures = new LongAdder();
|
||||
private final LongAdder auditFallbackMessages = new LongAdder();
|
||||
private final LongAdder auditLostMessages = new LongAdder();
|
||||
|
||||
public void auditLoss(long messages) { auditLostMessages.add(Math.max(0L, messages)); }
|
||||
public void auditWriteFailed(long messages) { auditWriteFailures.increment(); auditLoss(messages); }
|
||||
|
||||
public void record(List<BacklogRetentionDelta> deltas) {
|
||||
for (BacklogRetentionDelta delta : deltas) {
|
||||
@@ -51,6 +55,8 @@ public class BacklogSamplingMetrics {
|
||||
values.put("raw_dropped_total", rawDropped.sum());
|
||||
values.put("audit_write_failures_total", auditWriteFailures.sum());
|
||||
values.put("audit_fallback_messages_total", auditFallbackMessages.sum());
|
||||
values.put("audit_lost_or_unconfirmed_messages_total", auditLostMessages.sum());
|
||||
values.put("counter_semantics", "SAMPLING_DECISIONS_NOT_DB_CONFIRMATIONS");
|
||||
return values;
|
||||
}
|
||||
}
|
||||
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package com.common.service;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/** 辅助写库专用有界队列。入队不执行任务、不等待数据库、不使用CallerRuns。 */
|
||||
@Slf4j
|
||||
final class BestEffortAuxiliaryQueue {
|
||||
private final String kind;
|
||||
private final ArrayBlockingQueue<Task> queue;
|
||||
private final long maxGroups;
|
||||
private final boolean retry;
|
||||
private final AtomicLong groups = new AtomicLong();
|
||||
private final AtomicLong accepted = new AtomicLong();
|
||||
private final AtomicLong completed = new AtomicLong();
|
||||
private final AtomicLong failures = new AtomicLong();
|
||||
private final AtomicLong lost = new AtomicLong();
|
||||
private final AtomicLong logAfter = new AtomicLong();
|
||||
private volatile Task current;
|
||||
private volatile boolean closed;
|
||||
private volatile long resumeAt;
|
||||
private ScheduledExecutorService executor;
|
||||
|
||||
BestEffortAuxiliaryQueue(String kind, int capacity, long maxGroups, boolean retry) {
|
||||
this.kind = kind;
|
||||
this.queue = new ArrayBlockingQueue<>(capacity);
|
||||
this.maxGroups = maxGroups;
|
||||
this.retry = retry;
|
||||
}
|
||||
|
||||
void start() {
|
||||
executor = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "syslog-aux-" + kind.toLowerCase(java.util.Locale.ROOT));
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
executor.scheduleWithFixedDelay(this::drain, 0, 200, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
boolean offer(int weight, Runnable work) {
|
||||
boolean reserved = false;
|
||||
try {
|
||||
if (closed || weight < 1) { loss("CLOSED_OR_INVALID", null); return false; }
|
||||
long value;
|
||||
do {
|
||||
value = groups.get();
|
||||
if (weight > maxGroups - value) { loss("GROUP_LIMIT", null); return false; }
|
||||
} while (!groups.compareAndSet(value, value + weight));
|
||||
reserved = true;
|
||||
if (!queue.offer(new Task(weight, work))) { loss("QUEUE_FULL", null); return false; }
|
||||
reserved = false;
|
||||
accepted.incrementAndGet();
|
||||
return true;
|
||||
} catch (RuntimeException failure) {
|
||||
loss("ENQUEUE_FAILED", failure);
|
||||
return false;
|
||||
} finally {
|
||||
if (reserved) groups.addAndGet(-weight);
|
||||
}
|
||||
}
|
||||
|
||||
// 只有后台线程/测试调用;入队和状态查询不获取该锁。
|
||||
synchronized void drain() {
|
||||
if (resumeAt != 0L && System.nanoTime() < resumeAt) return;
|
||||
for (int n = 0; n < 32 && !closed; n++) {
|
||||
if (current == null) current = queue.poll();
|
||||
Task task = current;
|
||||
if (task == null || (task.retryAt != 0L && System.nanoTime() < task.retryAt)) return;
|
||||
long begin = System.nanoTime();
|
||||
long queueMs = TimeUnit.NANOSECONDS.toMillis(begin - task.createdAt);
|
||||
try {
|
||||
task.work.run();
|
||||
completed.incrementAndGet();
|
||||
groups.addAndGet(-task.weight);
|
||||
current = null;
|
||||
long workMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin);
|
||||
if (workMs >= 500 || queueMs >= 500) log.warn(
|
||||
"[SLOW_SYSLOG_AUX] kind={}, groups={}, queueAgeMs={}, executeMs={}, status=SUCCESS",
|
||||
kind, task.weight, queueMs, workMs);
|
||||
} catch (RuntimeException failure) {
|
||||
failures.incrementAndGet();
|
||||
if (retry) {
|
||||
task.retryAt = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
|
||||
} else {
|
||||
groups.addAndGet(-task.weight);
|
||||
current = null;
|
||||
lost.incrementAndGet();
|
||||
}
|
||||
if (mayLog()) log.error("[SYSLOG_AUX_FAILURE] kind={}, groups={}, queueAgeMs={}, executeMs={}, "
|
||||
+ "action={}, failuresTotal={}", kind, task.weight, queueMs,
|
||||
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin),
|
||||
retry ? "BACKGROUND_RETRY" : "DROP_AUX_ONLY", failures.get(), failure);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void loss(String reason, RuntimeException failure) {
|
||||
lost.incrementAndGet();
|
||||
if (mayLog()) log.error("[SYSLOG_AUX_LOSS] kind={}, reason={}, lostTasksTotal={}, action=CONTINUE_FACT_CONSUMPTION",
|
||||
kind, reason, lost.get(), failure);
|
||||
}
|
||||
|
||||
void pause(long millis) {
|
||||
resumeAt = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(Math.max(1L, millis));
|
||||
}
|
||||
|
||||
private boolean mayLog() {
|
||||
long now = System.nanoTime();
|
||||
long after = logAfter.get();
|
||||
return (after == 0 || now >= after) && logAfter.compareAndSet(after, now + TimeUnit.SECONDS.toNanos(10));
|
||||
}
|
||||
|
||||
Map<String, Object> status() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("mode", "BEST_EFFORT_BACKGROUND");
|
||||
result.put("pending_tasks", queue.size() + (current == null ? 0 : 1));
|
||||
result.put("pending_groups", groups.get());
|
||||
result.put("max_groups", maxGroups);
|
||||
result.put("enqueued_total", accepted.get());
|
||||
result.put("completed_total", completed.get());
|
||||
result.put("failures_total", failures.get());
|
||||
result.put("lost_tasks_total", lost.get());
|
||||
return result;
|
||||
}
|
||||
|
||||
void stop() {
|
||||
closed = true;
|
||||
if (executor != null) executor.shutdownNow();
|
||||
if (groups.get() > 0) log.warn("[SYSLOG_AUX_SHUTDOWN_PENDING] kind={}, pendingGroups={}, action=AUX_DATA_MAY_BE_LOST",
|
||||
kind, groups.get());
|
||||
}
|
||||
|
||||
private static final class Task {
|
||||
final int weight;
|
||||
final Runnable work;
|
||||
final long createdAt = System.nanoTime();
|
||||
long retryAt;
|
||||
Task(int weight, Runnable work) { this.weight = weight; this.work = work; }
|
||||
}
|
||||
}
|
||||
+44
-58
@@ -21,12 +21,13 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.SortedMap;
|
||||
import java.util.TreeMap;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* 把当前事实事务的内存聚合结果写入同步投影或可靠异步投影入口。
|
||||
* 把当前事实事务的内存聚合结果交给提交后的有界异步统计队列。
|
||||
*
|
||||
* <p>DIRECT 默认只追加一条批次 Outbox;SHADOW/显式回退仍同步更新统计表。调用方必须
|
||||
* 已经开启事实事务,本类不会吞掉任何数据库异常。</p>
|
||||
* <p>DIRECT 连续消费优先,不写 Outbox 或统计表,统计异常记录后放行。
|
||||
* 历史 SHADOW 模式仍同步写影子投影,保留原有校验语义。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -64,7 +65,7 @@ public class DirectStatsProjectionWriter {
|
||||
private final StatsWriteModeProvider modeProvider;
|
||||
private final DirectStatsWriteMetrics metrics;
|
||||
private final StatsMaterializationPublisher materializationPublisher;
|
||||
private final StatsProjectionOutboxWriter projectionOutboxWriter;
|
||||
private final StatsProjectionAsyncPublisher asyncPublisher;
|
||||
|
||||
@Value("${stats.incremental.read-enabled:false}")
|
||||
private boolean readEnabled;
|
||||
@@ -94,62 +95,51 @@ public class DirectStatsProjectionWriter {
|
||||
StatsWriteModeProvider modeProvider,
|
||||
DirectStatsWriteMetrics metrics,
|
||||
StatsMaterializationPublisher materializationPublisher,
|
||||
StatsProjectionOutboxWriter projectionOutboxWriter) {
|
||||
StatsProjectionAsyncPublisher asyncPublisher) {
|
||||
this.jdbc = jdbc;
|
||||
this.modeProvider = modeProvider;
|
||||
this.metrics = metrics;
|
||||
this.materializationPublisher = materializationPublisher;
|
||||
this.projectionOutboxWriter = projectionOutboxWriter;
|
||||
this.asyncPublisher = asyncPublisher;
|
||||
}
|
||||
|
||||
public WriteResult writeStandardizedRows(List<Map<String, Object>> rows) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(rows == null ? 0 : rows.size());
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addStandardizedRows(rows);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
return project(rows == null ? 0 : rows.size(), () -> accumulator().addStandardizedRows(rows), false);
|
||||
}
|
||||
|
||||
public WriteResult writeStandardizedRow(Map<String, Object> row) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(row == null ? 0 : 1);
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addStandardizedRow(row);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
return project(row == null ? 0 : 1, () -> accumulator().addStandardizedRow(row), false);
|
||||
}
|
||||
|
||||
public WriteResult writeNonNormalRows(List<SyslogNonNormalMessage> messages) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(messages == null ? 0 : messages.size());
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addNonNormalRows(messages);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
return project(messages == null ? 0 : messages.size(), () -> accumulator().addNonNormalRows(messages), false);
|
||||
}
|
||||
|
||||
public WriteResult writeNonNormalInsert(SyslogNonNormalMessage message) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(message == null ? 0 : 1);
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addNonNormalInsert(message);
|
||||
return write(accumulator, elapsedMs(aggregateStarted));
|
||||
return project(message == null ? 0 : 1, () -> accumulator().addNonNormalInsert(message), false);
|
||||
}
|
||||
|
||||
public WriteResult writeNonNormalUpdate(SyslogNonNormalMessage oldValue, SyslogNonNormalMessage patch) {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(oldValue == null || patch == null ? 0 : 1);
|
||||
return project(oldValue == null || patch == null ? 0 : 1,
|
||||
() -> accumulator().addNonNormalUpdate(oldValue, patch), true);
|
||||
}
|
||||
|
||||
private WriteResult project(int rows, Supplier<DirectStatsAccumulator> build, boolean exact) {
|
||||
try {
|
||||
if (!shouldBuildAggregation()) {
|
||||
handleFactOnlyMode();
|
||||
return WriteResult.inactive(rows);
|
||||
}
|
||||
long started = System.nanoTime();
|
||||
DirectStatsAccumulator aggregate = build.get();
|
||||
return exact ? writeExactDeviceGroups(aggregate, elapsedMs(started))
|
||||
: write(aggregate, elapsedMs(started));
|
||||
} catch (RuntimeException failure) {
|
||||
if (!asynchronousProjection()) throw failure;
|
||||
metrics.recordFailure();
|
||||
asyncPublisher.recordLoss(rows, "AGGREGATION_OR_REGISTRATION_FAILED", failure);
|
||||
return WriteResult.inactive(rows);
|
||||
}
|
||||
long aggregateStarted = System.nanoTime();
|
||||
DirectStatsAccumulator accumulator = accumulator().addNonNormalUpdate(oldValue, patch);
|
||||
return writeExactDeviceGroups(accumulator, elapsedMs(aggregateStarted));
|
||||
}
|
||||
|
||||
public void recordTransactionRetry() {
|
||||
@@ -165,7 +155,8 @@ public class DirectStatsProjectionWriter {
|
||||
status.put("business_materialization_mode", asynchronousMaterialization()
|
||||
? "KAFKA_DIRTY_KEY" : "SYNCHRONOUS");
|
||||
status.put("daily_projection_write_mode", asynchronousProjection()
|
||||
? "DURABLE_OUTBOX" : "SYNCHRONOUS_MERGE");
|
||||
? "BEST_EFFORT_AFTER_COMMIT_KAFKA" : "SYNCHRONOUS_MERGE");
|
||||
status.put("async_publisher", asyncPublisher.status());
|
||||
return status;
|
||||
}
|
||||
|
||||
@@ -201,21 +192,16 @@ public class DirectStatsProjectionWriter {
|
||||
requireTransaction();
|
||||
|
||||
if (asynchronousProjection()) {
|
||||
try {
|
||||
long outboxStarted = System.nanoTime();
|
||||
projectionOutboxWriter.append(StatsProjectionOutboxEvent.fromAccumulator(accumulator));
|
||||
long outboxMs = elapsedMs(outboxStarted);
|
||||
int deviceGroups = effectiveDeviceEntries(accumulator).size();
|
||||
int ruleGroups = effectiveRuleEntries(accumulator).size();
|
||||
metrics.recordSuccess(accumulator.getInputRows(), deviceGroups, ruleGroups,
|
||||
aggregateMs, outboxMs, 0L);
|
||||
return WriteResult.direct(accumulator.getInputRows(), deviceGroups, ruleGroups,
|
||||
aggregateMs, outboxMs, 0L);
|
||||
} catch (RuntimeException failure) {
|
||||
metrics.recordFailure();
|
||||
throw new DirectStatsWriteException(
|
||||
"统计投影 Outbox 写入失败,事实事务必须整体回滚", failure);
|
||||
}
|
||||
long enqueueStarted = System.nanoTime();
|
||||
asyncPublisher.enqueueAfterCommit(StatsProjectionOutboxEvent.fromAccumulator(accumulator),
|
||||
accumulator.getInputRows());
|
||||
long enqueueMs = elapsedMs(enqueueStarted);
|
||||
int deviceGroups = effectiveDeviceEntries(accumulator).size();
|
||||
int ruleGroups = effectiveRuleEntries(accumulator).size();
|
||||
metrics.recordSuccess(accumulator.getInputRows(), deviceGroups, ruleGroups,
|
||||
aggregateMs, enqueueMs, 0L);
|
||||
return WriteResult.direct(accumulator.getInputRows(), deviceGroups, ruleGroups,
|
||||
aggregateMs, enqueueMs, 0L);
|
||||
}
|
||||
|
||||
List<Map.Entry<DirectStatsAccumulator.DailyKey, DirectStatsAccumulator.DeviceDelta>> devices =
|
||||
@@ -438,8 +424,8 @@ public class DirectStatsProjectionWriter {
|
||||
}
|
||||
|
||||
private boolean asynchronousProjection() {
|
||||
return modeProvider.getMode() == StatsWriteModeProvider.Mode.DIRECT
|
||||
&& projectionOutboxWriter != null && projectionOutboxWriter.isEnabled();
|
||||
// 关闭统计发布也绝不回退同步统计SQL,以免再次阻塞事实消费。
|
||||
return modeProvider.getMode() == StatsWriteModeProvider.Mode.DIRECT;
|
||||
}
|
||||
|
||||
private List<StatsMaterializationCommand> materializationCommands(
|
||||
|
||||
+43
-5
@@ -36,6 +36,9 @@ public class DmStandardizedBatchExecutor {
|
||||
@org.springframework.beans.factory.annotation.Value("${stats.direct.transaction-log-enabled:false}")
|
||||
private boolean transactionLogEnabled;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Value("${syslog.slow-batch.threshold-ms:500}")
|
||||
private long slowTransactionThresholdMs;
|
||||
|
||||
@org.springframework.beans.factory.annotation.Value("${stats.direct.max-concurrency-retries:1}")
|
||||
private int maxConcurrencyRetries;
|
||||
|
||||
@@ -96,11 +99,14 @@ public class DmStandardizedBatchExecutor {
|
||||
transaction.setTimeout(Math.max(1, transactionTimeoutSeconds));
|
||||
long transactionStarted = System.nanoTime();
|
||||
final TransactionTiming timing = new TransactionTiming();
|
||||
try {
|
||||
transaction.execute(status -> {
|
||||
timing.beginMs = elapsedMs(transactionStarted);
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
|
||||
@Override
|
||||
public void beforeCommit(boolean readOnly) {
|
||||
timing.commitStarted = System.nanoTime();
|
||||
timing.phase("FACT_COMMIT");
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -110,31 +116,56 @@ public class DmStandardizedBatchExecutor {
|
||||
});
|
||||
long flushStarted = System.nanoTime();
|
||||
// 事实表使用一个固定 PreparedStatement 直接 addBatch,彻底绕开逐行 OGNL 动态 SQL。
|
||||
timing.phase("JDBC_FACT_WRITE");
|
||||
timing.batchExecution = preparedBatchInserter.insert(
|
||||
alarmTable, rows, transactionTimeoutSeconds);
|
||||
|
||||
// 兼容期变更日志仍与事实行共用当前事务;默认关闭时完全不创建 MyBatis BatchSession。
|
||||
if (statsChangeCaptureService.isEnabled()) {
|
||||
timing.phase("LEGACY_STATS_CAPTURE");
|
||||
statsChangeCaptureService.captureStandardizedBatch(batchSqlSession, rows, alarmTable);
|
||||
batchSqlSession.flushStatements();
|
||||
}
|
||||
timing.factFlushMs = elapsedMs(flushStarted);
|
||||
|
||||
// 与标准化告警事实共用同一事务写入事件时间桶。事实成功而通知失败时必须整体回滚,
|
||||
// 否则迟到数据可能永久失去重放机会。
|
||||
// 只注册提交后入队;分钟桶在独立后台事务写入,失败不回滚当前告警。
|
||||
if (alarmTable) {
|
||||
timing.phase("LATE_BUCKET_REGISTER");
|
||||
long bucketStarted = System.nanoTime();
|
||||
lateAlarmBucketWriter.record(rows);
|
||||
timing.lateBucketMs = elapsedMs(bucketStarted);
|
||||
}
|
||||
|
||||
// DIRECT 异步投影模式只在当前事实事务追加一条聚合 Outbox;独立 Kafka consumer
|
||||
// 再更新日统计。SHADOW/回退模式仍保留原同步 MERGE。
|
||||
// DIRECT 只聚合并注册afterCommit入队;此处不写Outbox/统计表、不发送Kafka。
|
||||
// 独立后台线程发送统计事件,失败不影响事实提交;历史SHADOW模式保留同步MERGE。
|
||||
timing.phase("STATS_REGISTER");
|
||||
timing.statsResult = directStatsProjectionWriter.writeStandardizedRows(rows);
|
||||
return null;
|
||||
});
|
||||
} catch (RuntimeException failure) {
|
||||
log.error("[SLOW_DM_TRANSACTION] batchId={}, table={}, factRows={}, status=FAILED, "
|
||||
+ "failureStage={}, phaseElapsedMs={}, transactionMs={}, connectionBeginMs={}, "
|
||||
+ "jdbcExecuteMs={}, lateAlarmBucketMs={}, retry={}, errorType={}",
|
||||
org.slf4j.MDC.get("syslogBatchId"), alarmTable ? "syslog_normal_alarm" : "syslog_normal_data",
|
||||
rows.size(), timing.phase, elapsedMs(timing.phaseStarted), elapsedMs(transactionStarted),
|
||||
timing.beginMs, timing.batchExecution.getExecuteMs(), timing.lateBucketMs, retries,
|
||||
failure.getClass().getName());
|
||||
throw failure;
|
||||
}
|
||||
long transactionMs = elapsedMs(transactionStarted);
|
||||
transactionMetrics.recordSuccess(rows.size(), timing.batchExecution.getPlanMs(),
|
||||
timing.batchExecution.getBindMs(), timing.batchExecution.getExecuteMs(),
|
||||
timing.factFlushMs, timing.commitMs, transactionMs);
|
||||
if (slowTransactionThresholdMs > 0 && transactionMs >= slowTransactionThresholdMs) {
|
||||
log.warn("[SLOW_DM_TRANSACTION] batchId={}, table={}, factRows={}, status=SUCCESS, connectionBeginMs={}, jdbcPlanMs={}, "
|
||||
+ "jdbcBindMs={}, jdbcExecuteMs={}, lateAlarmBucketMs={}, statsProjectionStageMs={}, "
|
||||
+ "commitMs={}, transactionMs={}, retry={}",
|
||||
org.slf4j.MDC.get("syslogBatchId"), alarmTable ? "syslog_normal_alarm" : "syslog_normal_data", rows.size(), timing.beginMs,
|
||||
timing.batchExecution.getPlanMs(), timing.batchExecution.getBindMs(),
|
||||
timing.batchExecution.getExecuteMs(), timing.lateBucketMs,
|
||||
timing.statsResult == null ? 0L : timing.statsResult.getMergeMs(),
|
||||
timing.commitMs, transactionMs, retries);
|
||||
}
|
||||
if (transactionLogEnabled && timing.statsResult != null && timing.statsResult.isDirect()) {
|
||||
log.info("DIRECT 达梦事务完成: factRows={}, deviceGroups={}, ruleGroups={}, aggregateMs={}, " +
|
||||
"jdbcPlanMs={}, jdbcBindMs={}, jdbcExecuteMs={}, factFlushMs={}, "
|
||||
@@ -148,7 +179,9 @@ public class DmStandardizedBatchExecutor {
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
return transactionMetrics.snapshot();
|
||||
Map<String, Object> result = transactionMetrics.snapshot();
|
||||
result.put("late_alarm_bucket_async", lateAlarmBucketWriter.status());
|
||||
return result;
|
||||
}
|
||||
|
||||
private static long elapsedMs(long startedNanos) {
|
||||
@@ -156,6 +189,11 @@ public class DmStandardizedBatchExecutor {
|
||||
}
|
||||
|
||||
private static final class TransactionTiming {
|
||||
private String phase = "CONNECTION_BEGIN";
|
||||
private long phaseStarted = System.nanoTime();
|
||||
private void phase(String value) { phase = value; phaseStarted = System.nanoTime(); }
|
||||
private long beginMs;
|
||||
private long lateBucketMs;
|
||||
private long factFlushMs;
|
||||
private long commitStarted;
|
||||
private long commitMs;
|
||||
|
||||
+18
@@ -69,6 +69,9 @@ public class DmStandardizedBatchWriter {
|
||||
@Value("${dm.standardized-write.batch-size:500}")
|
||||
private int batchSize;
|
||||
|
||||
@Value("${syslog.slow-batch.threshold-ms:500}")
|
||||
private long slowQueueThresholdMs;
|
||||
|
||||
@Value("${dm.standardized-write.transaction-timeout-seconds:45}")
|
||||
private int transactionTimeoutSeconds;
|
||||
|
||||
@@ -190,10 +193,25 @@ public class DmStandardizedBatchWriter {
|
||||
List<CompletableFuture<WriteReport<T>>> futures = new ArrayList<>(groups.size());
|
||||
try {
|
||||
for (Map.Entry<BatchKey, List<WriteRequest<T>>> entry : groups.entrySet()) {
|
||||
long queuedAt = System.nanoTime();
|
||||
String batchId = org.slf4j.MDC.get("syslogBatchId");
|
||||
futures.add(CompletableFuture.supplyAsync(() -> {
|
||||
String previous = org.slf4j.MDC.get("syslogBatchId");
|
||||
if (batchId != null) org.slf4j.MDC.put("syslogBatchId", batchId);
|
||||
else org.slf4j.MDC.remove("syslogBatchId");
|
||||
try {
|
||||
long queueMs = (System.nanoTime() - queuedAt) / 1_000_000L;
|
||||
if (slowQueueThresholdMs > 0 && queueMs >= slowQueueThresholdMs) {
|
||||
log.warn("[SLOW_DM_QUEUE] batchId={}, alarmTable={}, rows={}, queueMs={}",
|
||||
batchId, entry.getKey().alarmTable, entry.getValue().size(), queueMs);
|
||||
}
|
||||
WriteReport<T> groupReport = new WriteReport<>();
|
||||
writeGroup(entry.getKey(), entry.getValue(), groupReport, budget);
|
||||
return groupReport;
|
||||
} finally {
|
||||
if (previous == null) org.slf4j.MDC.remove("syslogBatchId");
|
||||
else org.slf4j.MDC.put("syslogBatchId", previous);
|
||||
}
|
||||
}, writerExecutor));
|
||||
}
|
||||
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.Modules.NormalData.SyslogFailureRouter;
|
||||
import com.common.entity.IngressStatsEvent;
|
||||
import com.common.util.Sm4Util;
|
||||
import com.common.util.SyslogParser;
|
||||
import com.config.AppProperties;
|
||||
import com.influx.raw.ReceiveTimeParser;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.kafka.annotation.KafkaListener;
|
||||
import org.springframework.kafka.support.Acknowledgment;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/** 独立消费原始Topic,只维护接收时间;不执行规则、采样或事实表写入。 */
|
||||
@Component
|
||||
@Slf4j
|
||||
public class IngressStatsConsumer {
|
||||
private final IngressStatsProjectionWriter writer;
|
||||
private final SyslogFailureRouter failureRouter;
|
||||
private final AppProperties appProperties;
|
||||
private final AtomicLong batches = new AtomicLong();
|
||||
private final AtomicLong invalidAttempts = new AtomicLong();
|
||||
private final AtomicLong writeFailures = new AtomicLong();
|
||||
|
||||
@Value("${spring.kafka.consumer.group-id}") private String rawGroup;
|
||||
@Value("${syslog.large-listener.group-id:${spring.kafka.consumer.group-id}-large}")
|
||||
private String largeRawGroup;
|
||||
@Value("${stats.ingress-metadata.group-id:${spring.kafka.consumer.group-id}-ingress-v1}")
|
||||
private String group;
|
||||
@Value("${stats.ingress-metadata.large-group-id:${stats.ingress-metadata.group-id}-large}")
|
||||
private String largeGroup;
|
||||
|
||||
public IngressStatsConsumer(IngressStatsProjectionWriter writer,
|
||||
SyslogFailureRouter failureRouter, AppProperties appProperties) {
|
||||
this.writer = writer;
|
||||
this.failureRouter = failureRouter;
|
||||
this.appProperties = appProperties;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void validateGroups() {
|
||||
if (group == null || group.trim().isEmpty() || largeGroup == null || largeGroup.trim().isEmpty()
|
||||
|| group.equals(largeGroup) || group.equals(rawGroup) || group.equals(largeRawGroup)
|
||||
|| largeGroup.equals(rawGroup) || largeGroup.equals(largeRawGroup)) {
|
||||
throw new IllegalStateException("入口统计必须使用与主消费隔离的非空 Kafka group-id");
|
||||
}
|
||||
log.info("Ingress stats consumer ready: group={}, largeGroup={}, mode=INDEPENDENT_KAFKA_DIRECT_MERGE",
|
||||
group, largeGroup);
|
||||
}
|
||||
|
||||
@KafkaListener(id = "syslog-ingress-stats", groupId = "${stats.ingress-metadata.group-id}",
|
||||
topics = "${spring.kafka.consumer.topic}",
|
||||
autoStartup = "${stats.ingress-metadata.enabled:true}",
|
||||
containerFactory = "ingressStatsKafkaListenerContainerFactory")
|
||||
public void consume(List<ConsumerRecord<String, String>> records, Acknowledgment ack) {
|
||||
consumeBatch(records, ack, "RAW");
|
||||
}
|
||||
|
||||
@KafkaListener(id = "syslog-ingress-stats-large", groupId = "${stats.ingress-metadata.large-group-id}",
|
||||
topics = "${spring.kafka.consumer.large-topic}",
|
||||
autoStartup = "#{${stats.ingress-metadata.enabled:true} && ${syslog.large-listener.enabled:true}}",
|
||||
containerFactory = "largeIngressStatsKafkaListenerContainerFactory")
|
||||
public void consumeLarge(List<ConsumerRecord<String, String>> records, Acknowledgment ack) {
|
||||
consumeBatch(records, ack, "RAW_LARGE");
|
||||
}
|
||||
|
||||
private void consumeBatch(List<ConsumerRecord<String, String>> records, Acknowledgment ack, String lane) {
|
||||
long started = System.nanoTime();
|
||||
List<IngressStatsEvent> events = new ArrayList<>(records.size());
|
||||
int invalid = 0;
|
||||
String firstInvalid = null;
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
try {
|
||||
events.add(decode(record));
|
||||
} catch (RuntimeException malformed) {
|
||||
invalid++;
|
||||
if (firstInvalid == null) firstInvalid = record.topic() + "-" + record.partition()
|
||||
+ "@" + record.offset() + ":" + malformed.getClass().getSimpleName();
|
||||
}
|
||||
}
|
||||
if (invalid > 0) {
|
||||
invalidAttempts.addAndGet(invalid);
|
||||
// 原始消息仍留在Kafka;坏头不会永久挡住其它设备接收状态,也不向业务Retry重复投递。
|
||||
log.error("[INGRESS_STATS_INVALID] lane={}, invalidRecords={}, firstInvalid={}, "
|
||||
+ "action=SKIP_INVALID_METADATA", lane, invalid, firstInvalid);
|
||||
}
|
||||
int groups;
|
||||
try {
|
||||
groups = writer.writeBatch(events);
|
||||
} catch (RuntimeException failure) {
|
||||
writeFailures.incrementAndGet();
|
||||
log.error("[INGRESS_STATS_WRITE_FAILED] lane={}, records={}, action=RETRY_STATS_GROUP",
|
||||
lane, records.size(), failure);
|
||||
throw failure;
|
||||
}
|
||||
// MIN/MAX更新和达梦提交均已完成,才推进独立统计组;重复消费不重复增加事实数量。
|
||||
ack.acknowledge();
|
||||
batches.incrementAndGet();
|
||||
log.info("[INGRESS_STATS_BATCH] lane={}, records={}, valid={}, invalid={}, groups={}, totalMs={}",
|
||||
lane, records.size(), events.size(), invalid, groups, (System.nanoTime() - started) / 1_000_000L);
|
||||
}
|
||||
|
||||
IngressStatsEvent decode(ConsumerRecord<String, String> record) {
|
||||
SyslogFailureRouter.MessageContext context = failureRouter.resolve(record);
|
||||
String decrypted = Sm4Util.decryptCbc(context.getPayload(), appProperties.getSm4Key());
|
||||
if (decrypted.indexOf(']') < 0) throw new IllegalArgumentException("缺少设备元数据头");
|
||||
Map<String, String> header = SyslogParser.parseKeyValuePairs(
|
||||
SyslogParser.substringBeforeFirstChar(decrypted, ']'));
|
||||
Long device = positiveId(header.get("device_id"));
|
||||
Long collector = positiveId(header.get("device_collect_id"));
|
||||
if (device == null && collector == null) throw new IllegalArgumentException("缺少有效设备/采集任务ID");
|
||||
return new IngressStatsEvent(context.getEventId(), device, collector,
|
||||
ReceiveTimeParser.parse(header.get("receive_time")).getLocalDateTime());
|
||||
}
|
||||
|
||||
private static Long positiveId(String value) {
|
||||
if (value == null || value.trim().isEmpty()) return null;
|
||||
long parsed = Long.parseLong(value);
|
||||
return parsed > 0L ? parsed : null;
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("group_id", group);
|
||||
result.put("large_group_id", largeGroup);
|
||||
result.put("successful_batches", batches.get());
|
||||
result.put("invalid_record_attempts", invalidAttempts.get());
|
||||
result.put("write_failures", writeFailures.get());
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+2
-15
@@ -29,7 +29,6 @@ public class IngressStatsProjectionWriter {
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final StatsWriteModeProvider modeProvider;
|
||||
private final StatsMaterializationPublisher materializationPublisher;
|
||||
private final StatsProjectionOutboxWriter projectionOutboxWriter;
|
||||
|
||||
@Value("${stats.ingress-metadata.enabled:false}")
|
||||
private boolean enabled;
|
||||
@@ -51,13 +50,11 @@ public class IngressStatsProjectionWriter {
|
||||
public IngressStatsProjectionWriter(JdbcTemplate jdbc,
|
||||
PlatformTransactionManager transactionManager,
|
||||
StatsWriteModeProvider modeProvider,
|
||||
StatsMaterializationPublisher materializationPublisher,
|
||||
StatsProjectionOutboxWriter projectionOutboxWriter) {
|
||||
StatsMaterializationPublisher materializationPublisher) {
|
||||
this.jdbc = jdbc;
|
||||
this.transactionManager = transactionManager;
|
||||
this.modeProvider = modeProvider;
|
||||
this.materializationPublisher = materializationPublisher;
|
||||
this.projectionOutboxWriter = projectionOutboxWriter;
|
||||
}
|
||||
|
||||
public int writeBatch(List<IngressStatsEvent> events) {
|
||||
@@ -95,8 +92,7 @@ public class IngressStatsProjectionWriter {
|
||||
? "device_daily_stats+" + shadowDeviceTable : "device_daily_stats");
|
||||
status.put("business_materialization_mode", asynchronousMaterialization()
|
||||
? "KAFKA_DIRTY_KEY" : "SYNCHRONOUS");
|
||||
status.put("daily_projection_write_mode", asynchronousProjection()
|
||||
? "DURABLE_OUTBOX" : "SYNCHRONOUS_MERGE");
|
||||
status.put("daily_projection_write_mode", "INDEPENDENT_KAFKA_DIRECT_MERGE");
|
||||
status.put("successful_batches", successfulBatches.get());
|
||||
status.put("received_events", receivedEvents.get());
|
||||
status.put("updated_groups", updatedGroups.get());
|
||||
@@ -114,10 +110,6 @@ public class IngressStatsProjectionWriter {
|
||||
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
|
||||
transaction.setTimeout(Math.max(1, transactionTimeoutSeconds));
|
||||
Integer updated = transaction.execute(status -> {
|
||||
if (asynchronousProjection()) {
|
||||
projectionOutboxWriter.append(StatsProjectionOutboxEvent.fromIngress(aggregation));
|
||||
return aggregation.devices.size() + aggregation.collects.size();
|
||||
}
|
||||
int groups = 0;
|
||||
boolean asyncMaterialization = asynchronousMaterialization();
|
||||
List<StatsMaterializationCommand> commands = asyncMaterialization
|
||||
@@ -246,11 +238,6 @@ public class IngressStatsProjectionWriter {
|
||||
&& materializationPublisher.isEnabled();
|
||||
}
|
||||
|
||||
private boolean asynchronousProjection() {
|
||||
return modeProvider.getMode() == StatsWriteModeProvider.Mode.DIRECT
|
||||
&& projectionOutboxWriter != null && projectionOutboxWriter.isEnabled();
|
||||
}
|
||||
|
||||
private static String safeTable(String table) {
|
||||
if (table == null || !table.matches("[A-Za-z][A-Za-z0-9_]*")) {
|
||||
throw new IllegalStateException("非法入口设备统计表名: " + table);
|
||||
|
||||
+51
-7
@@ -3,7 +3,8 @@ package com.common.service;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.TreeSet;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
@@ -12,11 +13,15 @@ import java.util.UUID;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
/**
|
||||
* 在标准化告警事实事务内登记事件时间桶。
|
||||
* 告警提交后登记事件时间桶,后台独立事务失败只重试通知,不回滚告警。
|
||||
*
|
||||
* <p>该通知不是“告警一定迟到”的结论。通知与事实在同一事务提交;下游能领取通知时,事实必然
|
||||
* <p>该通知不是“告警一定迟到”的结论。事实提交后才入队;下游能领取通知时,事实必然
|
||||
* 已经可见,再根据领取时已经完成的规则窗口决定是否重放。这里刻意不使用事实的
|
||||
* {@code created_at} 判断提交先后,因为 Kafka 积压时接收时间可能早于实际入库时间。
|
||||
*/
|
||||
@@ -38,12 +43,22 @@ public class LateAlarmBucketWriter {
|
||||
+ "VALUES (?,?,?,?,SYSDATE,1,0,0,'PENDING',0,0,SYSDATE,SYSDATE)";
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
private final BestEffortAuxiliaryQueue queue = new BestEffortAuxiliaryQueue("LATE_ALARM_BUCKET", 256, 50000, true);
|
||||
|
||||
@Value("${analysis.late-replay.notify-timeout-seconds:5}")
|
||||
private int transactionTimeoutSeconds = 5;
|
||||
|
||||
@javax.annotation.PostConstruct public void start() { queue.start(); }
|
||||
@javax.annotation.PreDestroy public void stop() { queue.stop(); }
|
||||
public Map<String, Object> status() { return queue.status(); }
|
||||
|
||||
@Value("${analysis.late-replay.outbox-enabled:true}")
|
||||
private boolean enabled;
|
||||
|
||||
public LateAlarmBucketWriter(JdbcTemplate jdbcTemplate) {
|
||||
public LateAlarmBucketWriter(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.transactionManager = transactionManager;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,7 +71,27 @@ public class LateAlarmBucketWriter {
|
||||
return;
|
||||
}
|
||||
|
||||
Set<BucketKey> buckets = new LinkedHashSet<>();
|
||||
try {
|
||||
// 只保留设备/分钟的小键,不把原始日志和事实行滞留在后台队列。
|
||||
Set<BucketKey> buckets = buckets(rows);
|
||||
if (!TransactionSynchronizationManager.isActualTransactionActive()
|
||||
|| !TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
throw new IllegalStateException("迟到告警通知必须在事实提交后入队");
|
||||
}
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override public void afterCommit() {
|
||||
queue.offer(buckets.size(), () -> writeBuckets(buckets));
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException failure) {
|
||||
queue.loss("PREPARE_OR_REGISTER_FAILED", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<BucketKey> buckets(List<Map<String, Object>> rows) {
|
||||
// 不同Kafka批次可能含有相反顺序的设备/分钟,统一加锁顺序避免交叉等待。
|
||||
Set<BucketKey> buckets = new TreeSet<>(Comparator
|
||||
.comparing((BucketKey key) -> key.deviceId).thenComparing(key -> key.bucketStart));
|
||||
for (Map<String, Object> row : rows) {
|
||||
Integer deviceId = integerValue(row.get("device_id"));
|
||||
LocalDateTime eventTime = timeValue(row.get("log_time"));
|
||||
@@ -65,7 +100,14 @@ public class LateAlarmBucketWriter {
|
||||
}
|
||||
buckets.add(new BucketKey(deviceId, eventTime.truncatedTo(ChronoUnit.MINUTES)));
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
private void writeBuckets(Set<BucketKey> buckets) {
|
||||
TransactionTemplate transaction = new TransactionTemplate(transactionManager);
|
||||
transaction.setPropagationBehavior(org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
transaction.setTimeout(Math.max(1, transactionTimeoutSeconds));
|
||||
transaction.execute(status -> {
|
||||
for (BucketKey key : buckets) {
|
||||
LocalDateTime bucketEnd = key.bucketStart.plusMinutes(1);
|
||||
try {
|
||||
@@ -79,14 +121,16 @@ public class LateAlarmBucketWriter {
|
||||
Timestamp.valueOf(bucketEnd));
|
||||
} catch (RuntimeException failure) {
|
||||
// 多个 Kafka 分区可能同时首次写同一设备分钟,MERGE 的并发插入会竞争唯一键。
|
||||
// 交给外层事实事务整体回滚并有限重试,不能只吞掉 outbox 失败。
|
||||
// 仅后台通知事务回滚重试,绝不返回事实事务。
|
||||
if (isConcurrentWrite(failure)) {
|
||||
throw new DirectStatsProjectionWriter.ConcurrentStatsWriteException(
|
||||
"迟到告警分钟桶并发写入失败,可安全回滚后有限重试", failure);
|
||||
"迟到告警分钟桶并发写入失败,仅后台通知事务回滚重试", failure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private Integer integerValue(Object value) {
|
||||
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.kafka.clients.producer.ProducerConfig;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
|
||||
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
|
||||
import org.springframework.kafka.core.KafkaTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
/** 连续消费优先:事实提交后只做有界内存offer,Kafka发送与重试在独立线程执行。 */
|
||||
@Slf4j
|
||||
@Component
|
||||
public class StatsProjectionAsyncPublisher {
|
||||
private final KafkaTemplate<String, String> kafka;
|
||||
private final ObjectMapper mapper;
|
||||
private final ArrayBlockingQueue<Pending> queue;
|
||||
private final long maxPendingGroups;
|
||||
private final AtomicLong pendingGroups = new AtomicLong();
|
||||
private final AtomicLong enqueued = new AtomicLong();
|
||||
private final AtomicLong published = new AtomicLong();
|
||||
private final AtomicLong failures = new AtomicLong();
|
||||
private final AtomicLong droppedEvents = new AtomicLong();
|
||||
private final AtomicLong droppedFactRows = new AtomicLong();
|
||||
private final AtomicLong nextLossLogAt = new AtomicLong();
|
||||
private volatile boolean closed;
|
||||
private volatile Pending inFlight;
|
||||
private ScheduledExecutorService executor;
|
||||
private DefaultKafkaProducerFactory<String, String> ownedProducerFactory;
|
||||
|
||||
// 与旧统计路径使用相同的 mapper;显式区分 WebConfig 的 httpObjectMapper。
|
||||
// 下方构造器复制后关闭类型信息,不修改共享缓存 mapper。
|
||||
@Autowired
|
||||
public StatsProjectionAsyncPublisher(KafkaProperties properties,
|
||||
@Qualifier("objectMapper") ObjectMapper mapper,
|
||||
@Value("${stats.projection-async.memory-queue-capacity:1000}") int capacity,
|
||||
@Value("${stats.projection-async.memory-max-pending-groups:50000}") long maxPendingGroups) {
|
||||
this(dedicatedFactory(properties), mapper, capacity, maxPendingGroups);
|
||||
}
|
||||
|
||||
private StatsProjectionAsyncPublisher(DefaultKafkaProducerFactory<String, String> factory,
|
||||
ObjectMapper mapper, int capacity, long maxPendingGroups) {
|
||||
this(new KafkaTemplate<>(factory), mapper, capacity, maxPendingGroups);
|
||||
this.ownedProducerFactory = factory;
|
||||
}
|
||||
|
||||
private static DefaultKafkaProducerFactory<String, String> dedicatedFactory(KafkaProperties properties) {
|
||||
Map<String, Object> config = new LinkedHashMap<>(properties.buildProducerProperties());
|
||||
config.put(ProducerConfig.CLIENT_ID_CONFIG, "syslog-stats-projection-memory");
|
||||
// 不与主业务Retry/DLT/告警发送共用KafkaProducer缓冲区,统计断链只影响后台发送。
|
||||
return new DefaultKafkaProducerFactory<>(config);
|
||||
}
|
||||
|
||||
@Value("${stats.projection-async.enabled:true}") private boolean enabled;
|
||||
@Value("${stats.projection-async.topic:${spring.kafka.consumer.topic}.STATS.PROJECTION}") private String topic;
|
||||
@Value("${stats.projection-async.publish-timeout-ms:10000}") private long timeoutMs;
|
||||
@Value("${stats.projection-async.retry-backoff-ms:1000}") private long retryBackoffMs;
|
||||
|
||||
StatsProjectionAsyncPublisher(KafkaTemplate<String, String> kafka, ObjectMapper mapper,
|
||||
int capacity, long maxPendingGroups) {
|
||||
if (capacity < 1 || maxPendingGroups < 1) throw new IllegalArgumentException("统计内存队列容量必须大于0");
|
||||
this.kafka = kafka;
|
||||
this.mapper = mapper.copy();
|
||||
this.mapper.deactivateDefaultTyping();
|
||||
this.queue = new ArrayBlockingQueue<>(capacity);
|
||||
this.maxPendingGroups = maxPendingGroups;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void start() {
|
||||
executor = Executors.newSingleThreadScheduledExecutor(task -> {
|
||||
Thread thread = new Thread(task, "stats-projection-publisher");
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
});
|
||||
executor.scheduleWithFixedDelay(this::flush, 0, 200, TimeUnit.MILLISECONDS);
|
||||
log.info("Stats projection publisher ready: mode=BEST_EFFORT_AFTER_COMMIT_KAFKA, enabled={}, "
|
||||
+ "queueCapacity={}, maxPendingGroups={}, topic={}",
|
||||
enabled, queue.remainingCapacity(), maxPendingGroups, topic);
|
||||
}
|
||||
|
||||
public void enqueueAfterCommit(StatsProjectionOutboxEvent event, int factRows) {
|
||||
try {
|
||||
event.validate();
|
||||
event.setOutboxBacked(false);
|
||||
if (!TransactionSynchronizationManager.isActualTransactionActive()
|
||||
|| !TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
throw new IllegalStateException("统计事件必须在事实事务提交后入队");
|
||||
}
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override public void afterCommit() {
|
||||
// 不做序列化、网络发送或数据库写入,任何运行时失败均不得影响已提交事实。
|
||||
offer(event, factRows);
|
||||
}
|
||||
});
|
||||
} catch (RuntimeException failure) {
|
||||
recordLoss(factRows, "PREPARE_OR_REGISTER_FAILED", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private void offer(StatsProjectionOutboxEvent event, int factRows) {
|
||||
long groups = (long) event.getDevices().size() + event.getRules().size() + event.getCollects().size();
|
||||
boolean reserved = false;
|
||||
try {
|
||||
if (!enabled || closed) {
|
||||
recordLoss(factRows, closed ? "SHUTTING_DOWN" : "PROJECTION_DISABLED", null);
|
||||
return;
|
||||
}
|
||||
long current;
|
||||
do {
|
||||
current = pendingGroups.get();
|
||||
if (groups > maxPendingGroups - current) {
|
||||
recordLoss(factRows, "GROUP_CAPACITY", null);
|
||||
return;
|
||||
}
|
||||
} while (!pendingGroups.compareAndSet(current, current + groups));
|
||||
reserved = true;
|
||||
if (queue.offer(new Pending(event, groups))) {
|
||||
reserved = false; // 预算归队列/发送线程所有,发送成功后释放。
|
||||
enqueued.incrementAndGet();
|
||||
} else {
|
||||
recordLoss(factRows, "QUEUE_FULL", null);
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
recordLoss(factRows, "ENQUEUE_FAILED", failure);
|
||||
} finally {
|
||||
if (reserved) pendingGroups.addAndGet(-groups);
|
||||
}
|
||||
}
|
||||
|
||||
/** 独立线程每轮最多发送100个聚合事件;失败保留原eventId,下游可去重。 */
|
||||
synchronized void flush() {
|
||||
if (!enabled || closed) return;
|
||||
for (int i = 0; i < 100 && !closed; i++) {
|
||||
if (inFlight == null) inFlight = queue.poll();
|
||||
Pending pending = inFlight;
|
||||
if (pending == null || pending.retryAt > System.currentTimeMillis()) return;
|
||||
try {
|
||||
if (pending.payload == null) pending.payload = mapper.writeValueAsString(pending.event);
|
||||
kafka.send(topic, StatsProjectionOutboxEvent.KAFKA_KEY, pending.payload)
|
||||
.get(Math.max(1L, timeoutMs), TimeUnit.MILLISECONDS);
|
||||
published.incrementAndGet();
|
||||
pendingGroups.addAndGet(-pending.groups);
|
||||
inFlight = null;
|
||||
} catch (Exception failure) {
|
||||
failures.incrementAndGet();
|
||||
pending.retryAt = System.currentTimeMillis() + Math.max(1000L, retryBackoffMs);
|
||||
log.warn("[STATS_ASYNC_PUBLISH_FAILED] eventId={}, pendingEvents={}, action=BACKGROUND_RETRY, errorType={}",
|
||||
pending.event.getEventId(), queue.size() + 1, failure.getClass().getName());
|
||||
if (failure instanceof InterruptedException) Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void recordLoss(int factRows, String reason, RuntimeException failure) {
|
||||
droppedEvents.incrementAndGet();
|
||||
droppedFactRows.addAndGet(Math.max(0, factRows));
|
||||
long now = System.currentTimeMillis();
|
||||
long next = nextLossLogAt.get();
|
||||
if (now >= next && nextLossLogAt.compareAndSet(next, now + 10000L)) {
|
||||
log.error("[STATS_ASYNC_LOSS] reason={}, droppedEventsTotal={}, droppedFactRowsTotal={}, "
|
||||
+ "action=CONTINUE_FACT_CONSUMPTION, errorType={}", reason, droppedEvents.get(),
|
||||
droppedFactRows.get(), failure == null ? "none" : failure.getClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> status() {
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("mode", "BEST_EFFORT_AFTER_COMMIT_KAFKA");
|
||||
result.put("enabled", enabled);
|
||||
result.put("topic", topic);
|
||||
result.put("pending_events", queue.size() + (inFlight == null ? 0 : 1));
|
||||
result.put("queue_capacity", queue.size() + queue.remainingCapacity());
|
||||
result.put("pending_groups", pendingGroups.get());
|
||||
result.put("max_pending_groups", maxPendingGroups);
|
||||
result.put("enqueued_total", enqueued.get());
|
||||
result.put("published_total", published.get());
|
||||
result.put("publish_failures_total", failures.get());
|
||||
result.put("dropped_events_total", droppedEvents.get());
|
||||
result.put("dropped_fact_rows_total", droppedFactRows.get());
|
||||
return result;
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void stop() {
|
||||
closed = true;
|
||||
if (executor != null) executor.shutdownNow();
|
||||
int pending = queue.size() + (inFlight == null ? 0 : 1);
|
||||
if (pending > 0) log.warn("[STATS_ASYNC_SHUTDOWN_PENDING] pendingEvents={}, "
|
||||
+ "pendingGroups={}, action=STATISTICS_MAY_BE_LOST", pending, pendingGroups.get());
|
||||
if (ownedProducerFactory != null) ownedProducerFactory.destroy();
|
||||
}
|
||||
|
||||
private static final class Pending {
|
||||
final StatsProjectionOutboxEvent event;
|
||||
final long groups;
|
||||
String payload;
|
||||
long retryAt;
|
||||
Pending(StatsProjectionOutboxEvent event, long groups) { this.event = event; this.groups = groups; }
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -211,11 +211,11 @@ public class StatsProjectionDeltaConsumer {
|
||||
jdbc.batchUpdate("INSERT INTO " + StatsProjectionOutboxWriter.safeTable(appliedTable) +
|
||||
" (event_id,event_schema,applied_at) VALUES (?,?,SYSDATE)", markers);
|
||||
}
|
||||
if (!events.isEmpty()) {
|
||||
List<Object[]> acknowledged = new ArrayList<>(events.size());
|
||||
for (StatsProjectionOutboxEvent event : events) {
|
||||
acknowledged.add(new Object[]{event.getEventId()});
|
||||
}
|
||||
List<Object[]> acknowledged = new ArrayList<>();
|
||||
for (StatsProjectionOutboxEvent event : events) {
|
||||
if (event.isOutboxBacked()) acknowledged.add(new Object[]{event.getEventId()});
|
||||
}
|
||||
if (!acknowledged.isEmpty()) {
|
||||
jdbc.batchUpdate("UPDATE " + StatsProjectionOutboxWriter.safeTable(outboxTable) +
|
||||
" SET status='APPLIED',applied_at=SYSDATE,next_attempt_at=NULL," +
|
||||
"updated_at=SYSDATE WHERE event_id=?", acknowledged);
|
||||
|
||||
+6
-1
@@ -10,7 +10,7 @@ import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A durable, batch-aggregated statistics delta written beside the fact rows.
|
||||
* Batch-aggregated delta shared by the after-commit memory publisher and legacy durable Outbox.
|
||||
*
|
||||
* <p>The event is additive/max-min only, so events from different application nodes may be
|
||||
* published in a different order without changing the final projection. Kafka duplicates are
|
||||
@@ -23,6 +23,11 @@ public class StatsProjectionOutboxEvent {
|
||||
|
||||
private String schema = SCHEMA;
|
||||
private String eventId = UUID.randomUUID().toString();
|
||||
// 老版消息没有此字段,默认true,兼容清理升级前的Outbox。
|
||||
private boolean outboxBacked = true;
|
||||
|
||||
public boolean isOutboxBacked() { return outboxBacked; }
|
||||
public void setOutboxBacked(boolean outboxBacked) { this.outboxBacked = outboxBacked; }
|
||||
private List<DeviceDelta> devices = new ArrayList<>();
|
||||
private List<RuleDelta> rules = new ArrayList<>();
|
||||
private List<CollectDelta> collects = new ArrayList<>();
|
||||
|
||||
Reference in New Issue
Block a user