SpringBoot事务相关
原创2025/7/14...小于 1 分钟
1. Spring 事务事件
使用场景
- 事务成功后发送通知
- 事务成功后更新缓存
- 事务回滚后的补偿操作
需要开启异步配置,任何一个配置类或者启动类添加注解@EnableAsync
定义事件
@Slf4j
@Component
public class ReportGenerationEvent extends ApplicationEvent {
private final Long recordId;
public ReportGenerationEvent(Object source, Long recordId) {
super(source);
this.recordId = recordId;
}
public Long getRecordId() {
return recordId;
}
}
发布事件
@Resource
private ApplicationEventPublisher eventPublisher;
// 含有事务的方法中使用
eventPublisher.publishEvent(new ReportGenerationEvent(this, recordId));
创建事件监听器
@Component
public class ReportEventListener {
@Resource
private ReportService reportService;
// 使用你定义的线程池进行异步处理,核心!确保在事务成功提交后才执行
@Async("threadPoolTaskExecutor")
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleReportGenerationEvent(ReportGenerationEvent event) {
try {
reportService.generatePreDiagnosisReport(event.getRecordId());
} catch (Exception e) {
log.error("出现异常: {}", e.getMessage(), e);
}
}
}