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) -> {

final CompletableFuture<QueryResult> queryResultCompletableFuture

= connection.sendPreparedStatement("select 0");

ctx.result(

queryResultCompletableFuture

.thenApply((t) -> "got result: " + 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.SERVER_STARTING, () -> {

logger.info("--- SERVER STARTING!");

connection.connect().get();

logger.info("--- connection STARTED!");

})

.event(JavalinEvent.SERVER_STOPPING, () -> {

logger.info("--- SERVER STOPPING!");

connection.disconnect().get();

logger.info("--- connection STOPPED!");

})

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.