【问题标题】:Transactions in webflux with blocking spring datawebflux 中的事务与阻塞 spring 数据
【发布时间】:2021-12-19 15:48:06
【问题描述】:

鉴于:带有 webflux 的反应式系统,带有 jdbc 驱动程序的传统 spring 数据,我如何使用以下方法管理事务:

Mono<TrxResponse> doTrx(){
return Mono.fromCallable(() -> parentRepository.save(parent))
                   .flatMap(parent()-> {
                    return Mono.fromCallable(() -> childRepository.save(child)})
                   .flatmap(resp -> {return new TrxResponse()}); 
} 

【问题讨论】:

  • Spring 发表了一篇关于使用 webflux 进行事务的博客。它可能值得一读。 spring.io/blog/2019/05/16/reactive-transactions-with-spring
  • 当您使用响应式应用程序时,我还建议不要使用阻塞数据库驱动程序,而是使用响应式驱动程序,例如 r2dbc
  • 一些有经验的人强烈建议不要使用 r2dbc。就我而言,驱动程序仍然有未修复的错误,还没有准备好生产。我的希望全在于反应式休眠 + vert.x。
  • 是的,有 r2dbc 的替代品,我建议您探索所有这些并选择最适合您的用例的一个。 R2DBC 只是作为一个例子。尽管如果您想了解反应式系统的全部好处,我仍然建议您使用反应式数据库驱动程序。

标签: spring-webflux spring-transactions


【解决方案1】:

您可以使用对 DB 的阻塞更新方法实现单独的事务层,例如:

class TransactionRepo {

    private TransactionTemplate transactionTemplate;
    
    // save to DB method
    public Void saveObjects(Parent parent, Child child) {
        saveParent(parent);
        savechild(child);
    }
    
    // your reactive method 
    public Mono<Void> saveObjectsAsync(Parent parent, Child child) {
        return Mono.fromCallable(() -> transactionTemplate.execute(transactionStatus -> 
            saveObjects(parent, child)));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2018-06-09
    • 2019-09-25
    • 2020-10-09
    • 2020-09-18
    • 2021-06-04
    • 2019-11-18
    相关资源
    最近更新 更多