Over a million developers have joined DZone.

Vert.x and Fiber: Perfect Synergy!

DZone's Guide to

Vert.x and Fiber: Perfect Synergy!

Vert.x might be your go-to tool suite for Reactive apps, but take a look at how Fibers can allow you to receive events synchronously.

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Presumably, you have already heard of Vert.x, a toolkit for building Reactive applications on the JVM. Vert.x is completely asynchronous, lightweight, incredibly fast, event-driven, and definitely a very promising project. Some of you may have heard about Fibers — if you're not familiar with them, check here and here. In addition to Vert.x's non-blocking and event-driven toolkit, we can take advantage of Vertx-Sync as a component through which we can easily escape from well-known callback hell while using non-blocking APIs. Vertx-Sync allows you to perform asynchronous operations and receive events in a synchronous way, but without blocking kernel threads. As a result, even if  it’s synchronous, it is negligibly less performant. Vertx-Sync uses Quasar to provide its Fibers.

In this article, I’ll show you how to:

  1. Create a simple Vert.x project.
  2. Write simple and concise code via Vertx-Sync.  
  3. Create a simple REST API via Vertx-Web.
  4. Get some web content using an HTTP client.
  5. Use MongoDB as an example for using a database with Vert.x.

You can head to GitHub to follow along here. For the sake of this blog, we need:

  1. JDK 1.8
  2. Maven
  3. MongoDB

Install and set up MongoDB

Download the latest version of MongoDB and unzip it to your local directory. You may download it from here. Then, make the following directory /data/db inside the directory where MongoDB is unzipped.

To start the server go to {mongo_directory}/bin and start mongod.

Now it is time to run the mongo client. Go to {mongo_directory}/bin and start mongo .

Create a testDB database and an Entities collection:

use testDB;

Create a Simple Vert.x Project

It’s time to create our Vert.x project. Let’s do it! Our starting point of the project is:

import io.vertx.core.Vertx;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

public class Launcher {
    private static final Logger logger = LoggerFactory.getLogger(MainVerticle.class);

    public static void main(String[] args) {
        Vertx.vertx().deployVerticle(MainVerticle.class.getName(), h -> {
            if (h.succeeded()) {
                logger.info("Success: {0}", h.result());
            } else {
                logger.error("Something went wrong: {0}", h.cause());

And our Vertical:

import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.ErrorHandler;

import java.util.List;

public class MainVerticle extends SyncVerticle {

    private static final Logger 
    logger = LoggerFactory.getLogger(MainVerticle.class);
    private static final String COLLECTION_NAME= "Entities";
    private WebClient webClient;
    private MongoClient mongoClient;

    public void start(Future<Void> startFuture) throws Exception {
        HttpServer server = vertx.createHttpServer();
        Router router = Router.router(vertx);
        // enable BodyHandler globally for easiness of body accessing
        // HttpServer will be automatically shared if port matches
        webClient = WebClient.create(vertx, new WebClientOptions().setSsl(true));
        mongoClient = MongoClient.createShared
       (vertx, new JsonObject().put("connection_string", "mongodb://"));

    private void saveNewEntity(RoutingContext routingContext){
        final String response = Sync.awaitResult
        (h ->  mongoClient.save(COLLECTION_NAME, routingContext.getBodyAsJson(), h));

    private void getAllEntities(RoutingContext routingContext){
        final List<JsonObject> entities = Sync.awaitResult
        (h ->  mongoClient.find(COLLECTION_NAME, new JsonObject(), h));

    private void getEntityById(RoutingContext routingContext){
        final JsonObject query = new JsonObject()
                .put("_id", routingContext.pathParam("id"));
        final List<JsonObject> entity = Sync.awaitResult
        (h ->  mongoClient.find(COLLECTION_NAME, query, h));

    private void getWebContent(RoutingContext routingContext){
        final HttpResponse<Buffer> response = Sync.awaitResult
        (h -> webClient.getAbs("https://www.google.com").send(h));
        final String responseContent = response.bodyAsString("UTF-8");
        logger.info("Result of Http request: {0}", responseContent);
                .putHeader(HttpHeaderNames.CONTENT_TYPE, "text/html")

  1. The Launcher class is just for starting our program and deploying our MainVerticle.
  2. It has to be considered that our MainVerticle extends io.vertx.ext.sync.SyncVerticle. If it is not deployed as a SyncVerticle instance, the Fibers will not work.
  3. Create HttpServer and a router for handling our REST API (following the next three steps):
    1. GET http://localhost:8089/getWebContent — request to “https://www.google.com” just for testing the async HTTP client.
    2. GET http://localhost:8089/entities
    3. GET http://localhost:8089/entities/:id  — :id is the path parameter for finding some entity
    4. PUT http://localhost:8089/entities — create a new entity record. Apply JSON to the payload, for example: {“name”: “Charlie Harper”}
  4. Create WebClient and MongoClient and use their async APIs synchronously via Fibers.
  5. It is very important to use Sync.fiberHandler() when we need to use any handlers. For usage of Fibers in a normal handler, for example in the request handler of an HTTP server, we must first convert the normal handler to a fiber handler.
  6. Getting a response from async APIs that return AsyncResult<T>  as a callback is very easy with Sync.awaitResult(). Below is some copied documentation from Vertx about it:

"Many async operations in Vert.x-land take a Handler<AsyncResult<T>> as the last argument. An example would be executing a find using the Vert.x Mongo client or sending an event bus message and getting a reply. Vertx-sync allows you to get the result of a one-shot asynchronous operation in a synchronous way. This is done by using the Sync.awaitResult method."

The method is executed specifying the asynchronous operation that you want to execute in the form of a Consumer, the consumer is passed the handler at run-time. Using Lambda expressions makes it even easier:

final List<JsonObject> entity = Sync.awaitResult
(h ->  mongoClient.find(COLLECTION_NAME, query, h));
final HttpResponse<Buffer> 
response = Sync.awaitResult
(h -> webClient.getAbs("https://www.google.com").send(h));

The most important thing is to instrument our bytecode. Vert.x uses Quasar and their Fiber implementation use bytecode instrumentation. We don’t need to do anything special, but just have to start the JVM with javaagent as the VM option. For example:


For that, we use “exec-maven-plugin” . That is the content of pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"






Finally, to start our program, just type: mvn clean package exec:java

And that is all!

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

java ,vert.x ,fiber ,reactive ,tutorial ,async

Published at DZone with permission of Nikolay Petkov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}