Reactive database transaction with Vertx
Intro
Recently I needed to create an app using Micronaut’s Reactor for my work, fundamentally it makes your JVM application run in an unblocking manner and thus increases the throughput.
The project needs to do database transactions and since documentation does not contain the integration with Micronaut’s reactor core library, I am writing this post.
If you want to check the documentation from the micronaut page you can check this link.
The code
I am writing this in Groovy, but it will be similar if you write it in Java or other JVM languages.
1 | package transactionvertx |
Breakdown
1 | pool.rxGetConnection().flatMap { c -> |
We are starting by getting a connection from the pool, if you already have the connection you can use that instead. By calling .flatMap
I am using the connection and returning the non-blocking (another Observable) function call which is c.rxBegin()
to begin the transaction.
1 | return c.rxBegin().flatMap { trx -> } |
Now we have a Transaction
object from the connection, we are going to use this to control our transaction.
We start our transaction by calling c.rxBegin()
.
1 | c.query("INSERT INTO my_user(name, email) VALUES('John John 1', 'mayerjohn1@mail.com')").rxExecute() |
Using the connection we got earlier, do the query normally and call rxExecute()
to return an Observable
version of the query.
1 | .doOnError { trx.rollback() } |
Then finish the transaction by calling rollback or commit depending on what happened in the transaction, one important note is always close()
your connection when the transaction is finished to return it to the pool.
full code here.