在Spring中将操作附加到回滚

我们在Spring Boot应用程序中存在一个问题,该应用程序在数据库事务期间创建了一些文件,如果事务回滚,则需要将其删除。 这是我的解决方案...

创建文件后,我们将发布一个包含文件名的事件:

applicationEventPublisher.publishEvent(new FileCreatedEvent(this, filename));

我们还有另一个监听事件的组件:

@TransactionalEventListener(phase = TransactionPhase.AFTER_ROLLBACK)
public void handleRollback(FileCreatedEvent event) {
    fileDeleter.delete(event.getFilename()); 
}

As you can see, Spring Framework provides a pub/sub event management feature where you can publish an event using 一种pplicationEventPublisher (which can easily be autowired). You can then subscribe to the event using a @TransactionalEventListener annotation 1, which can be tailored to fire only after a rollback by setting the phase parameter on the annotation to 一种FTER_ROLLBACK (as shown).

至关重要的是,在事务解决之前,事件不会传递给侦听器。 这使事务处理逻辑变得更加简单。此外,它还可以处理附加到同一事务的多个同时发生的事件,这意味着您可以为每个文件触发离散事件,并且每个事件都将在事务完成时传递。

此模式的另一潜在用途是,通过触发新条目的事件来防止误导日志/审计条目,但仅在事务成功提交时和何时记录该事件。 这样,除非真正创建了新实体,否则您不会看到日志消息显示“在数据库中创建了新实体”。

1 This pattern also works without transactions if you subscribe using a simple @EventListener. In this case, the event would be handled immediately by the listener, rather than waiting until the end of the transaction.

from: https://dev.to//virtualmackem/attaching-actions-to-rollbacks-in-spring-g1g

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值