全屏浏览
缩小浏览
回到页首

spring---->Spring事务与ApplicationEventPublisher

Spring事务与ApplicationEventPublisher

@Transactional
public void handle() {
    var account = Account.builder()
            .username("huhx")
            .password("pass")
            .build();
    accountRepository.save(account);
    publisher.publishEvent(new AccountEvent("huhx"));
    var account2 = Account.builder()
            .username("huhx2")
            .password("pass2")
            .build();
    accountRepository.save(account2);
}

@Component
@RequiredArgsConstructor
public class AccountEventHandler {

    private final BookService bookService;

    @EventListener(AccountEvent.class)
    public void onAccountEvent(AccountEvent event) {
        bookService.save(new BookRequest(event.username()));

        throw new RuntimeException();
    }
}

// 1. No books saved, no account saved

// 2. add @Transactional on onAccountEvent, No books saved, no account saved

// 3. add @Async on onAccountEvent, two accounts saved, one book saved

// 4. add @Async and @Transactional on onAccountEvent, only two accounts saved

// 5. execute in Thread and with @Transactional, two accounts saved, one book saved(这里加不加@Transactional,没区别)
@Transactional
@EventListener(AccountEvent.class)
public void handle(AccountEvent event) {
    new Thread(() -> {
        bookService.save(new BookRequest(event.username()));
        throw new RuntimeException();
    }).start();
}

// 6. change the eventHandle code as following, no accounts saved, only one book saved(这里加不加@Transactional,没区别)
@Transactional
@EventListener(AccountEvent.class)
public void handle(AccountEvent event) {
    new Thread(() -> bookService.save(new BookRequest(event.username()))).start();
    bookService.save(new BookRequest(event.username()));
    throw new RuntimeException();
}

默认情况下,ApplicationEventPublisher的publishEvent方法是同步的


posted @   huhx  阅读(193)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2016-04-06 java基础---->Java的格式化输出
2016-04-06 java高级---->Java动态代理的原理
点击右上角即可分享
微信分享提示