我们在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.