What is Vert.x

Reading Time: 4 minutes
vertx-logo

Vert.x is an open-source, reactive polyglot platform or toolkit that runs on the JVM(Java Virtual Machine). We can think vert.x as an alternative to the JEE(Java Enterprise Edition). It  provides a convenient way to implement reactive applications on the JVM. Reactive applications consists of components that send messages or events to each other. 

Re­ac­tive ap­pli­ca­tions are both scal­able as work­loads grow, and re­silient when fail­ures arise. Moreover, A re­ac­tive ap­pli­ca­tion is re­spon­sive as it keeps la­tency under con­trol by mak­ing ef­fi­cient usage of sys­tem re­sources, and by pro­tect­ing it­self from er­rors.

Vert.x is backed with a large ecosys­tem of re­ac­tive mod­ules with just any­thing you need, when writ­ing mod­ern ser­vices: a com­pre­hen­sive web stack, re­ac­tive data­base dri­vers, mes­sag­ing, event streams, clus­ter­ing, met­rics, dis­trib­uted trac­ing and more.

It comes with a different approach in the market to solve the issues such as developing networked and highly concurrent applications.

Vert.x is a toolkit to build distributed reactive systems on the top of the Java Virtual Machine using an asynchronous and non-blocking development model. We can use Vert.x as a toolkit in a standalone application or embedded in a Spring application by instantiate a Vert.x object and call methods on it to get Vert.x and do whatever we need. It does not provide an all-in-one solution, but provides the building blocks to build your own solution.

Vert.x is polyglot means, it allows you to write event-driven applications by developing components in the language that you think most appropriate for the task, such as Java itself, Kotlin, Scala, Ruby, and JavaScript.

It is event-driven, single-threaded, and non-blocking, which means you can handle many concurrent apps with a small number of threads.In this way, it lets your app scale with minimal hardware. It operates a single event loop, but it also has the ability to keep a thread pool to match the number of available cores. With greater concurrency support, Vert.x is suitable for not only IO but also CPU-heavy processes that require parallel computing.

working-diagram-of-vertx
A working diagram of Vert.x services.

Vert.x has some core concepts

– Verticle

– Event Loop

– Event Bus

Verticle

Verticles are chunks of code that get deployed and run. Verticles allow you to encapsulate your code for different needs, and can be run independently of each other.

An application would typically be composed of many verticle instances running in the same Vert.x instance at the same time. Verticle instances communicate with each other by sending messages on the event bus.

Event Loop

The event loop of Vert.x is similar in the existing asynchronous programming models. The method requestHandler is where the event loop delivers the request event. Its APIs are non-blocking and won’t block the event loop, but that’s not much help if you block the event loop yourself in a handler. But keep in mind the single important rule of non-blocking thread: don’t block it.

event loop image

Event Bus

The communication between the Verticles occurs through messages that are managed and delivered by the event bus, which accepts two types of implementation: point-to-point and publish/subscribe, though Vert.x doesn’t provide a guaranteed delivery of the messages. Hence, there is a single event bus instance for every Vert.x instance.

event bus working image

If you are developing a public API, then vertx-core should be enough. If it’s a web app, you may add vertx-web which provides http parameter handling and JWT/Session authentication. 

Let’s Code

To try out Vert.x, let’s create a simple Java project using maven.

Step-1: Create a new maven project and add vertx web dependency.

        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-web</artifactId>
            <version>4.2.3</version>
        </dependency>

public class MainVerticle extends AbstractVerticle {

  @Override
  public void start() throws Exception {
    // Create a Router
    Router router = Router.router(vertx);

    // Mount the handler for all incoming requests at every path and HTTP method
    router.route("/hello").handler(context -> {
      // Get the address of the request
      String address = context.request().connection().remoteAddress().toString();
      // Get the query parameter "name"
      MultiMap queryParams = context.queryParams();
      String name = queryParams.contains("name") ? queryParams.get("name") : "unknown";
      // Write a json response
      context.json(
        new JsonObject()
          .put("name", name)
          .put("address", address)
          .put("message", "Hello " + name + " connected from " + address)
      );
    });

    // Create the HTTP server
    vertx.createHttpServer()
      // Handle every request using the router
      .requestHandler(router)
      // Start listening
      .listen(8888)
      // Print the port
      .onSuccess(server ->
        System.out.println(
          "HTTP server started on port " + server.actualPort()
        )
      );
  }
}

The above code will create a vert.x web router and start an HTTP server on port 8888. It returns a JSON object on each request. The JSON object contains the query parameter names, the address of the request, and a greeting message.

To run the code, open a ter­mi­nal and nav­i­gate to your project folder. Build the ap­pli­ca­tion as fol­lows:

$ mvn package

Then, run the ap­pli­ca­tion:

$ mvn exec:java

showing output for mvn exec command

Now that the server is up and run­ning, try to send a re­quest:

We are going to send a request as:

$ http http://localhost:8888\?name\=”Aasif Ali”

Output:

Json output of the program

Conclusion

In this blog we have introduced vert.x library with example. The vert.x library is the evolving technology in the reactive programming and event driven applications.Vert.x gives you the freedom to make a slow transition from one language to another.

knoldus

Written by 

Aasif Ali is a Software Consultant at Knoldus Inc. He has done Post Graduation from Quantum University Roorkee. He has the knowledge of various programming languages. He is passionate about Java development and curious to learn Java Technologies. He is always impatient and enthusiastic to learn new things. He is a quick learner, problem solver and always enjoy to help others. His hobbies are watching Sci-fi movies , Playing badminton and listening to songs.