When writing Vert.x verticles, everything is about non-blocking asynchronous operations, of course. Therefore if we want to have Amazon DynamoDB as our database, we want to also call it asynchronously. In this example I assume you already created the DynamoDB table.
First we start with creating the asynchronous DynamoDB client:
Then we create our Vert.x verticle:
The book is being
POSTed as JSON, so to write it to DynamoDB we call
To make it even better, we can rewrite this to using coroutines instead. Coroutines is a new feature in Kotlin that allows for cleaning up some of these callbacks.
To have a nice integration between Kotlin coroutines and Vert.x, there is an additional Vert.x module you must add to your Gradle dependencies:
Read more about it here: http://vertx.io/docs/vertx-lang-kotlin-coroutines/kotlin/
Then you must extend
CoroutineVerticle instead of
Note that start has now become a suspending function. From this function you can call other suspending functions.
If we look at
PutItemAsync, it requires a
com.amazonaws.handlers.AsyncHandler as a callback. But actually we really want to use awaitResult provided by the Vert.x Kotlin Coroutines integration module, which requires a different callback:
io.vertx.core.Handler. Therefore we define our own coroutine that bridges the two:
Now we can use that to rewrite our handler:
Note that you must wrap a handler body in the
launch block, because you want to invoke a coroutine, but handlers themselves cannot be suspending.
This is described here: http://vertx.io/docs/vertx-lang-kotlin-coroutines/kotlin/#_handlers.
Using coroutines with Vert.x allows you to simplify a lot of callbacks to just code with standard exception handling. Much more readable!
- Async call DynamoDB from Vert.x using Kotlin coroutines
- My takeaways from Joy of Coding 2017
- Setting up a Docker Swarm cluster with Vagrant and Ansible
- OAuth 2.0 server with Facebook login in Spring Boot and Kotlin
- Kotlin binary search example