Deploying the verticles from a main verticle

We still have a MainVerticle class, but instead of containing all the business logic like in the initial iteration, its sole purpose is to bootstrap the application and deploy other verticles.

The code consists in deploying 1 instance of WikiDatabaseVerticle and 2 instances of HttpServerVerticle :

  1. public class MainVerticle extends AbstractVerticle {
  2. @Override
  3. public void start(Promise<Void> promise) throws Exception {
  4. Promise<String> dbVerticleDeployment = Promise.promise(); (1)
  5. vertx.deployVerticle(new WikiDatabaseVerticle(), dbVerticleDeployment); (2)
  6. dbVerticleDeployment.future().compose(id -> { (3)
  7. Promise<String> httpVerticleDeployment = Promise.promise();
  8. vertx.deployVerticle(
  9. "io.vertx.guides.wiki.HttpServerVerticle", (4)
  10. new DeploymentOptions().setInstances(2), (5)
  11. httpVerticleDeployment);
  12. return httpVerticleDeployment.future(); (6)
  13. }).setHandler(ar -> { (7)
  14. if (ar.succeeded()) {
  15. promise.complete();
  16. } else {
  17. promise.fail(ar.cause());
  18. }
  19. });
  20. }
  21. }
  1. Deploying a verticle is an asynchronous operation, so we need a Future for that. The String parametric type is because a verticle gets an identifier when successfully deployed.

  2. One option is to create a verticle instance with new, and pass the object reference to the deploy method. The completer return value is a handler that simply completes its future.

  3. Sequential composition with compose allows to run one asynchronous operation after the other. When the initial future completes successfully, the composition function is invoked.

  4. A class name as a string is also an option to specify a verticle to deploy. For other JVM languages string-based conventions allow a module / script to be specified.

  5. The DeploymentOption class allows to specify a number of parameters and especially the number of instances to deploy.

  6. The composition function returns the next future. Its completion will trigger the completion of the composite operation.

  7. We define a handler that eventually completes the MainVerticle start future.

The astute reader will probably wonder how we can deploy the code for a HTTP server on the same TCP port twice and not expect any error for either of the instances, since the TCP port will already be in use. With many web frameworks we would need to choose different TCP ports, and have a frontal HTTP proxy to perform load balancing between the ports.

There is no need to do that with Vert.x as multiple verticles can share the same TCP ports. Incoming connections are simply distributed in a round-robin fashion from accepting threads.