Async Java all the way to the database with jasync-sql and javalin

osha1
osha1
Sep 15, 2018 · 2 min read

Reactive and Async web-servers in Java are not as popular as I would like them to be. It is easier to do so than what you probably imagine.

In this post, I will show one way to implement an async web server with javalin and jasync-sql. The example source code is here:

Javalin is a configured embedded jetty, that is easy to configure in Java and Kotlin. In order to work with it in Reactive mode routes should be methods that returns CompleteableFuture of Java 8. That works great with jasync-sql since its sendQuery method returns CompletableFuture<QueryResult>.

Here is how it looks like:

app.get(, (ctx) -> {
CompletableFuture<QueryResult> queryResultCompletableFuture
= connection.sendPreparedStatement();
ctx.result(
queryResultCompletableFuture
.thenApply((t) -> + t.getRows().get(0).get(0))
);
});

In this example, we map the / route to go to the database for an empty query.

Photo by David Becker on Unsplash

In order to create the connection to the database and do the termination when server stops we can use javalin event mechanism. It looks like that:

.event(JavalinEvent., () -> {
.info();
connection.connect().get();
.info();
})
.event(JavalinEvent., () -> {
.info();
connection.disconnect().get();
.info();
})

Well, that’s it. You can see the full source code in GitHub: https://github.com/jasync-sql/jasync-sql/tree/master/samples/postgres-javalin

Hope that helps,

Enjoy!

P.S. — I am among the contributors of jasyc-sql, the project is fairly in its early stages so if you encounter any problem, don’t hesitate to open an issue.