Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Webflux with Transactions

Is it possible to have transaction management using Spring Webflux? We will be building a microservice and I'm considering using Spring Webflux but I'd like to make sure that a PUT/POST request that mutates state can be atomic. For example if the request that is received needs to:

  • Update state in the microservice's own database
  • Make an update to a downstream service via a REST API

Is it possible to wrap the steps within a Transaction so that the changes are atomic?

like image 885
n00b Avatar asked May 25 '18 05:05

n00b


People also ask

Does Spring support nested transactions?

Nested transactions in Spring are just JDBC / database savepoints. If you don't know what a savepoint is, have a look at this tutorial, for example. Note that savepoint support is dependent on your JDBC driver/database.

Why is ChainedTransactionManager deprecated?

ChainedTransactionManager (Deprecated) ChainedTransactionManager is a way of declaring multiple data sources, in which, in the case of exception, rollbacks will occur in the reverse order. Thus, with three data sources, if an error occurred during a commit on the second, only the first two will try to roll back.

How does Spring WebFlux work internally?

Spring WebFlux internally uses Project Reactor and its publisher implementations, Flux and Mono. The new framework supports two programming models: Annotation-based reactive components. Functional routing and handling.


1 Answers

You can use TransactionTemplate in your reactive code:

private TransactionTemplate transactionTemplate;

// save to DB method
public Void saveMembers(Member m1, Member m2) {
    saveMember(m1);
    saveMember(m2);
}

// your reactive method 
public Mono<Void> saveMembersAsync(Member m1, Member m) {
    return Mono.fromCallable(() -> transactionTemplate.execute(transactionStatus -> 
        saveMembers(m1, m2)));
}
like image 92
Yauhen Balykin Avatar answered Jan 03 '23 15:01

Yauhen Balykin