34 lines
1.3 KiB
Java
34 lines
1.3 KiB
Java
package com.baiyue.common.audit;
|
|||
|
|
|
||
|
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||
|
|
import org.slf4j.Logger;
|
||
|
|
import org.slf4j.LoggerFactory;
|
||
|
|
import org.springframework.transaction.support.TransactionOperations;
|
||
|
|
|
||
|
|
/** 将审计事件先持久化到业务库 Outbox,核心业务不等待 MQ。 */
|
||
|
|
public class OutboxAuditSink implements AuditSink {
|
||
|
|
private static final Logger log = LoggerFactory.getLogger(OutboxAuditSink.class);
|
||
|
|
private final AuditOutboxRepository repository;
|
||
|
|
private final ObjectMapper json;
|
||
|
|
private final TransactionOperations transactions;
|
||
|
|
|
||
|
|
public OutboxAuditSink(AuditOutboxRepository repository, ObjectMapper json,
|
||
|
|
TransactionOperations transactions) {
|
||
|
|
this.repository = repository;
|
||
|
|
this.json = json;
|
||
|
|
this.transactions = transactions;
|
||
|
|
}
|
||
|
|
|
||
|
|
@Override
|
||
|
|
public void publish(AuditEvent event) {
|
||
|
|
try {
|
||
|
|
String payload = json.writeValueAsString(event);
|
||
|
|
transactions.executeWithoutResult(status -> repository.append(event, payload));
|
||
|
|
} catch (JsonProcessingException | RuntimeException exception) {
|
||
|
|
log.error("审计事件写入本地 Outbox 失败 eventId={} eventType={}",
|
||
|
|
event.eventId(), event.eventType(), exception);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|