Vert.x and Reactive Programming


Vert.x was born when Tim Fox decided that he liked a lot of what was being developed in the NodeJS ecosystem, but he didn’t like some of the trade-offs of working in V8: Single-threadedness, limited library support, and JavaScript itself. Tim set out to write a toolkit which was unopinionated about how and where it is used, and he decided that the best place to implement it was on the JVM. So, Tim and the community set out to create an event-driven, non-blocking, reactive toolkit which in many ways mirrored what could be done in NodeJS, but also took advantage of the power available inside of the JVM. Node.x was born and it later progressed to become Vert.x.


Vert.x is designed to implement an event bus which is how different parts of the application can communicate in a non-blocking/thread safe manner. Parts of it were modeled after the Actor methodology exhibited by Eralng and Akka. It is also designed to take full advantage of today’s multi-core processors and highly concurrent programming demands. As such, by default, all Vert.x VERTICLES are implemented as single-threaded by default. Unlike NodeJS though, Vert.x can run MANY verticles in MANY threads. Additionally, you can specify that some verticles are “worker” verticles and CAN be multi-threaded. And to really add some icing on the cake, Vert.x has low level support for multi-node clustering of the event bus via the use of Hazelcast. It has gone on to include many other amazing features which are too numerous to list here, but you can read more in the official Vert.x docs.
The first thing you need to know about Vert.x is, similar to NodeJS, never block the current thread. Everything in Vert.x is set up, by default, to use callbacks/futures/promises. Instead of doing synchronous operations, Vert.x provides async methods for doing most I/O and processor intensive operations which might block the current thread. Now, callbacks can be ugly and painful to work with, so Vert.x optionally provides an API based on RxJava which implements the same functionality using the Observer pattern. Finally, Vert.x makes it easy to use your existing classes and methods by providing the executeBlocking(Function f) method on many of it’s asynchronous APIs. This means you can choose how you prefer to work with Vert.x instead of the toolkit dictating to you how it must be used.
The second thing to know about Vert.x is that it composed of verticles, modules, and nodes. Verticles are the smallest unit of logic in Vert.x, and are usually represented by a single class. Verticles should be simple and single-purpose following the UNIX Philosophy. A group of verticles can be put together into a module, which is usually packaged as a single JAR file. A module represents a group of related functionality which when taken together could represent an entire application or just a portion of a larger distributed application. Lastly, nodes are single instances of the JVM which are running one or more modules/verticles. Because Vert.x has clustering built-in from the ground up, Vert.x applications can span nodes either on a single machine or across multiple machines in multiple geographic locations (though latency can hider performance).

Example Project

Now, I’ve been to a number of Meetups and conferences lately where the first thing they show you when talking about reactive programming is to build a chat room application. That’s all well and good, but it doesn’t really help you to completely understand the power of reactive development. Chat room apps are simple and simplistic. We can do better. In this tutorial, we’re going to take a legacy Spring application and convert it to take advantage of Vert.x. This has multiple purposes: It shows that the toolkit is easy to integrate with existing Java projects, it allows us to take advantage of existing tools which may be entrenched parts of our ecosystem, and it also lets us follow the DRY principle in that we don’t have to rewrite large swathes of code to get the benefits of Vert.x.

Our legacy Spring application is a contrived simple example of a REST API using Spring Boot, Spring Data JPA, and Spring REST. The source code can be found in the “master” branch HERE. There are other branches which we will use to demonstrate the progression as we go, so it should be simple for anyone with a little experience with git and Java 8 to follow along. Let’s start by examining the Spring Configuration class for the stock Spring application.

05public class Application {
06    public static void main(String[] args) {
07        ApplicationContext ctx =, args);
09        System.out.println("Let's inspect the beans provided by Spring Boot:");
11        String[] beanNames = ctx.getBeanDefinitionNames();
12        Arrays.sort(beanNames);
13        for (String beanName : beanNames) {
14            System.out.println(beanName);
15        }
16    }
18    @Bean
19    public DataSource dataSource() {
20        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
21        return builder.setType(EmbeddedDatabaseType.HSQL).build();
22    }
24    @Bean
25    public EntityManagerFactory entityManagerFactory() {
26        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
27        vendorAdapter.setGenerateDdl(true);
29        LocalContainerEntityManagerFactoryBean factory = newLocalContainerEntityManagerFactoryBean();
30        factory.setJpaVendorAdapter(vendorAdapter);
31        factory.setPackagesToScan("");
32        factory.setDataSource(dataSource());
33        factory.afterPropertiesSet();
35        return factory.getObject();
36    }
38    @Bean
39    public PlatformTransactionManager transactionManager(final EntityManagerFactory emf) {
40        final JpaTransactionManager txManager = new JpaTransactionManager();
41        txManager.setEntityManagerFactory(emf);
42        return txManager;
43    }
As you can see at the top of the class, we have some pretty standard Spring Boot annotations. You’ll also see an @Slf4j annotation which is part of the lombok library, which is designed to help reduce boiler-plate code. We also have @Beanannotated methods for providing access to the JPA EntityManager, the TransactionManager, and DataSource. Each of these items provide injectable objects for the other classes to use. The remaining classes in the project are similarly simplistic. There is a Customer POJO which is the Entity type used in the service. There is a CustomerDAO which is created via Spring Data. Finally, there is a CustomerEndpoints class which is the JAX-RS annotated REST controller.

As explained earlier, this is all standard fare in a Spring Boot application. The problem with this application is that for the most part, it has limited scalability. You would either run this application inside of a Servlet container, or with an embedded server like Jetty or Undertow. Either way, each requests ties up a thread and is thus wasting resources when it waits for I/O operations.
Switching over to the Convert-To-Vert.x-Web branch, we can see that the Application class has changed a little. We now have some new @Bean annotated methods for injecting the Vertx instance itself, as well as an instance of ObjectMapper (part of the Jackson JSON library). We have also replaced the CustomerEnpoints class with a new CustomerVerticle. Pretty much everything else is the same.
The CustomerVerticle class is annotated with @Component, which means that Spring will instantiate that class on startup. It also has it’s start method annotated with @PostConstruct so that the Verticle is launched on startup. Looking at the actual content of the code, we see our first bits of Vert.x code: Router.
The Router class is part of the vertx-web library and allows us to use a fluent API to define HTTP URLs, methods, and header filters for our request handling. Adding the BodyHandler instance to the default route allows a POST/PUT body to be processed and converted to a JSON object which Vert.x can then process as part of the RoutingContext. The order of routes in Vert.x CAN be significant. If you define a route which has some sort of glob matching (* or regex), it can swallow requests for routes defined after it unless you implement chaining. Our example shows 3 routes initially.

02    public void start() throws Exception {
03        Router router = Router.router(vertx);
04        router.route().handler(BodyHandler.create());
05        router.get("/v1/customer/:id")
06                .produces("application/json")
07                .blockingHandler(this::getCustomerById);
08        router.put("/v1/customer")
09                .consumes("application/json")
10                .produces("application/json")
11                .blockingHandler(this::addCustomer);
12        router.get("/v1/customer")
13                .produces("application/json")
14                .blockingHandler(this::getAllCustomers);
15        vertx.createHttpServer().requestHandler(router::accept).listen(8080);
16    }
Notice that the HTTP method is defined, the “Accept” header is defined (via consumes), and the “Content-Type” header is defined (via produces). We also see that we are passing the handling of the request off via a call to the blockingHandlermethod. A blocking handler for a Vert.x route accepts a RoutingContext object as it’s only parameter. The RoutingContext holds the Vert.x Request object, Response object, and any parameters/POST body data (like “:id”). You’ll also see that I used method references rather than lambdas to insert the logic into the blockingHandler (I find it more readable). Each handler for the 3 request routes is defined in a separate method further down in the class. These methods basically just call the methods on the DAO, serialize or deserialize as needed, set some response headers, and end() the request by sending a response. Overall, pretty simple and straightforward.

01private void addCustomer(RoutingContext rc) {
02        try {
03            String body = rc.getBodyAsString();
04            Customer customer = mapper.readValue(body, Customer.class);
05            Customer saved =;
06            if (saved!=null) {
07                rc.response().setStatusMessage("Accepted").setStatusCode(202).end(mapper.writeValueAsString(saved));
08            } else {
09                rc.response().setStatusMessage("Bad Request").setStatusCode(400).end("Bad Request");
10            }
11        } catch (IOException e) {
12            rc.response().setStatusMessage("Server Error").setStatusCode(500).end("Server Error");
13            log.error("Server error", e);
14        }
15    }
17    private void getCustomerById(RoutingContext rc) {
18"Request for single customer");
19        Long id = Long.parseLong(rc.request().getParam("id"));
20        try {
21            Customer customer = dao.findOne(id);
22            if (customer==null) {
23                rc.response().setStatusMessage("Not Found").setStatusCode(404).end("Not Found");
24            } else {
25                rc.response().setStatusMessage("OK").setStatusCode(200).end(mapper.writeValueAsString(dao.findOne(id)));
26            }
27        } catch (JsonProcessingException jpe) {
28            rc.response().setStatusMessage("Server Error").setStatusCode(500).end("Server Error");
29            log.error("Server error", jpe);
30        }
31    }
33    private void getAllCustomers(RoutingContext rc) {
34"Request for all customers");
35        List customers =, false).collect(Collectors.toList());
36        try {
37            rc.response().setStatusMessage("OK").setStatusCode(200).end(mapper.writeValueAsString(customers));
38        } catch (JsonProcessingException jpe) {
39            rc.response().setStatusMessage("Server Error").setStatusCode(500).end("Server Error");
40            log.error("Server error", jpe);
41        }
42    }
“But this is more code and messier than my Spring annotations and classes”, you might say. That CAN be true, but it really depends on how you implement the code. This is meant to be an introductory example, so I left the code very simple and easy to follow. I COULD use an annotation library for Vert.x to implement the endpoints in a manner similar to JAX-RS. In addition, we have gained a massive scalability improvement. Under the hood, Vert.x Web uses Netty for low-level asynchronous I/O operations, thus providing us the ability to handle MANY more concurrent requests (limited by the size of the database connection pool).
We’ve already made some improvement to the scalability and concurrency of this application by using the Vert.x Web library, but we can improve things a little more by implementing the Vert.x EventBus. By separating the database operations into Worker Verticles instead of using blockingHandler, we can handle request processing more efficiently. This is show in the Convert-To-Worker-Verticles branch. The application class has remained the same, but we have changed the CustomerEndpoints class and added a new class called CustomerWorker. In addition, we added a new library called Spring Vert.x Extension which provides Spring Dependency Injections support to Vert.x Verticles. Start off by looking at the new CustomerEndpoints class.

02    public void start() throws Exception {
03"Successfully create CustomerVerticle");
04        DeploymentOptions deployOpts = newDeploymentOptions().setWorker(true).setMultiThreaded(true).setInstances(4);
05        vertx.deployVerticle("java-spring:com.zanclus.verticles.CustomerWorker", deployOpts, res -> {
06            if (res.succeeded()) {
07                Router router = Router.router(vertx);
08                router.route().handler(BodyHandler.create());
09                final DeliveryOptions opts = new DeliveryOptions()
10                        .setSendTimeout(2000);
11                router.get("/v1/customer/:id")
12                        .produces("application/json")
13                        .handler(rc -> {
14                            opts.addHeader("method""getCustomer")
15                                    .addHeader("id", rc.request().getParam("id"));
16                            vertx.eventBus().send("com.zanclus.customer"null, opts, reply -> handleReply(reply, rc));
17                        });
18                router.put("/v1/customer")
19                        .consumes("application/json")
20                        .produces("application/json")
21                        .handler(rc -> {
22                            opts.addHeader("method""addCustomer");
23                            vertx.eventBus().send("com.zanclus.customer", rc.getBodyAsJson(), opts, reply -> handleReply(reply, rc));
24                        });
25                router.get("/v1/customer")
26                        .produces("application/json")
27                        .handler(rc -> {
28                            opts.addHeader("method""getAllCustomers");
29                            vertx.eventBus().send("com.zanclus.customer"null, opts, reply -> handleReply(reply, rc));
30                        });
31                vertx.createHttpServer().requestHandler(router::accept).listen(8080);
32            else {
33                log.error("Failed to deploy worker verticles.", res.cause());
34            }
35        });
36    }
The routes are the same, but the implementation code is not. Instead of using calls to blockingHandler, we have now implemented proper async handlers which send out events on the event bus. None of the database processing is happening in this Verticle anymore. We have moved the database processing to a Worker Verticle which has multiple instances to handle multiple requests in parallel in a thread-safe manner. We are also registering a callback for when those events are replied to so that we can send the appropriate response to the client making the request. Now, in the CustomerWorker Verticle we have implemented the database logic and error handling.



Popular Posts