Spring Modulith 活动

问题描述 投票:0回答:1

我正在使用注释 @Transactional 注释的方法中发布事件。 侦听器带有 @TransactionalEventListener 注解。

上述设置导致同步(我们可以使用@Async来更改它)事件处理,并且事件也通过spring modulith事件本身存储到数据库中(我使用的是postgres)。

但是,如果我使发布者成为非事务性的(即删除 @Transactional 注释),则侦听器不会侦听并执行为其指定的事件。我们也无法获得数据库条目,因为没有侦听器能够处理它。

我可以将监听器更改为@EventListener来监听非事务性事件,但在这种情况下我失去了数据库事件持久性

我希望发布商可以自由决定是否要进行交易/非交易。无论如何,侦听器必须侦听并执行为其指定的事件,并将事件保存到数据库中。

请帮忙!

听众

    @TransactionalEventListener
    public void notificationEvent(ProductEvent event) {
        System.out.println("Listener 1 Start");
        System.out.println("Listener 1 End");
    }

出版商

//    @Transactional
    public void publishEvent() {
        System.out.println("Publisher Start");
        ProductEvent productEvent = new ProductEvent("Product A", "THIS IS PRODUCT", 777);
        applicationEventPublisher.publishEvent(productEvent);
        System.out.println("Publisher End");
    }
spring spring-boot events spring-events
1个回答
0
投票
  1. @TransactionalEventListener

    的本质
    • 它专门设计用于处理事务上下文中的事件。
    • 它确保事件侦听器在与发布方法相同的事务中执行。
    • 这种保证对于一致性和数据完整性至关重要。
  2. 交易同步

    • Spring 的事务基础设施依赖于事务同步。 事务中发布的事件与其生命周期同步。
    • 仅当事务成功提交时才会调用监听器。
  3. 非事务性上下文

    • 当事件在事务外部发布时,没有可同步的事务。
    • @TransactionalEventListener 机制不适用。

我不知道有任何 Spring boot 功能可以为您开箱即用。但是,您可以在捕获非事务性事件后启动新事务并将其手动保存在数据库中

© www.soinside.com 2019 - 2024. All rights reserved.