Create a Vert.x Event Bus Service with Service Proxy

This document will show you how to bootstrap an Event Bus service using Vert.x Service Proxy module. As you will see, this approach is particularly useful when you want to design and consume a service on the event bus using plain Java interfaces.

What you will build

You will build a Vert.x application that exposes and uses BarmanService, an Event Bus Service that generates beers and manages customer bills. We are going to deploy two verticles: the BarmanVerticle that exposes the service and the DrunkVerticle that consumes the service

What you need

  • A text editor or IDE

  • Java 8 higher

  • Maven

Create a project

Here is the content of the pom.xml file you should be using:

You must import both vertx-codegen with processor classifier and vertx-service-proxy. We are going to use vertx-web-client to load the beer names.

Design the BarmanService

First, we must define our service interface. Under the hood, a code generator analyze it and generates the event bus message handler and the proxy class.

This is the BarmanService interface:

package io.vertx.howtos.ebservice.beers;

import io.vertx.codegen.annotations.ProxyGen;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;

@VertxGen
@ProxyGen // (1)
public interface BarmanService {

  void giveMeARandomBeer(String customerName, Handler<AsyncResult<Beer>> handler); // (2)

  void getMyBill(String customerName, Handler<AsyncResult<Integer>> handler); // (3)

  void payMyBill(String customerName); // (4)

  static BarmanService createProxy(Vertx vertx, String address) { // (5)
    return new BarmanServiceVertxEBProxy(vertx, address);
  }

}
  1. Add @VertxGen and @ProxyGen to trigger code generation

  2. Define the method that generates a new beer and adds it to the bill of the customer specified. When the beer is ready, It calls the handler with the new beer

  3. Define the method that retrieves the bill.

  4. Define the method that settles the bill. This is a fire and forget method

  5. Specify the method that creates a new proxy. BarmanServiceVertxEBProxy is the class name of the proxy that the code generator will create for us

There are a couple of rules you must follow while defining the service interface. Look at Restrictions for service interface for more info. In our interface we are using a couple of primitives and Beer, a POJO annotated as @DataObject. If you want to use @DataObject`s inside your interface, they must define both a constructor with only a `JsonObject parameter and a toJson() method that returns a JsonObject

To trigger the code generation, you must also add in the same package of the interface a package-info.java with @ModuleGen annotation:

@ModuleGen(groupPackage = "io.vertx.howtos.ebservice", name = "beers")
package io.vertx.howtos.ebservice.beers;

import io.vertx.codegen.annotations.ModuleGen;

Implement the BarmanService

Now you can implement the BarmanService.

For giveMeARandomBeer():

@Override
public void giveMeARandomBeer(String customerName, Handler<AsyncResult<Beer>> handler) {
  webClient
    .get(443, "www.craftbeernamegenerator.com", "/api/api.php?type=classic")
    .ssl(true)
    .send(ar -> { // (1)
      if (ar.failed()) handler.handle(Future.failedFuture(ar.cause())); // (2)
      else {
        JsonObject result = ar.result().bodyAsJsonObject();
        if (result.getInteger("status") != 200) // (2)
          handler.handle(Future.failedFuture("Beer Generator Service replied with " + result.getInteger("status") + ": " + result.getString("status_message")));
        else {
          Beer beer = new Beer( // (3)
            result.getJsonObject("data").getString("name"),
            result.getJsonObject("data").getString("style"),
            3 + random.nextInt(5)
          );
          System.out.println("Generated a new Beer! " + beer);
          bills.merge(customerName, beer.getPrice(), (oldVal, newVal) -> oldVal + newVal); // (4)
          handler.handle(Future.succeededFuture(beer)); // (5)
        }
      }
    });
}
  1. Send a request to the Craft Beer Name Generator Service

  2. Fail the async method if the request to external service failed

  3. Create a new Beer

  4. Add the beer to the customer bill

  5. Complete the async method with the generated beer

For getMyBill():

@Override
public void getMyBill(String customerName, Handler<AsyncResult<Integer>> handler) {
  handler.handle(Future.succeededFuture(bills.get(customerName)));
}

For settleMyBill():

@Override
public void payMyBill(String customerName) {
  bills.remove(customerName);
  System.out.println("Removed debt of " + customerName);
}

Expose the service

Now we can expose the service inside the BarmanVerticle with the ServiceBinder class:

package io.vertx.howtos.ebservice;

import io.vertx.core.AbstractVerticle;
import io.vertx.ext.web.client.WebClient;
import io.vertx.howtos.ebservice.beers.BarmanService;
import io.vertx.howtos.ebservice.beers.impl.BarmanServiceImpl;
import io.vertx.serviceproxy.ServiceBinder;

public class BarmanVerticle extends AbstractVerticle {

  @Override
  public void start() {
    BarmanService service = new BarmanServiceImpl(WebClient.create(vertx)); // (1)

    new ServiceBinder(vertx) // (2)
      .setAddress("beers.services.myapplication") // (3)
      .register(BarmanService.class, service); // (4)
  }
}
  1. Instantiate the BarmanServiceImpl

  2. Instantiate the ServiceBinder

  3. Configure the service address

  4. Register the service on the event bus

Use the service

Now we can use the service with the generated proxy. For demo purposes I’m going to use it inside another verticle called DrunkVerticle:

package io.vertx.howtos.ebservice;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.howtos.ebservice.beers.BarmanService;

public class DrunkVerticle extends AbstractVerticle {

  @Override
  public void start(Promise<Void> startPromise) {
    BarmanService barmanService = BarmanService.createProxy(vertx, "beers.services.myapplication"); // (1)

    barmanService.giveMeARandomBeer("homer", b1 -> { // (2)
      if (b1.failed()) { // (3)
        System.err.println("Cannot get my first beer!");
        startPromise.fail(b1.cause());
        return;
      }
      System.out.println("My first beer is a " + b1.result() + " and it costs " + b1.result().getPrice() + "€"); // (4)
      vertx.setTimer(1500, l ->
        barmanService.giveMeARandomBeer("homer", b2 -> { // (5)
          if (b2.failed()) {
            System.out.println("Cannot get my second beer!");
            startPromise.fail(b2.cause());
            return;
          }
          System.out.println("My second beer is a " + b2.result() + " and it costs " + b2.result().getPrice() + "€"); // (6)
          barmanService.getMyBill("homer", billAr -> {
            System.out.println("My bill with the bar is " + billAr.result()); // (7)
            barmanService.payMyBill("homer"); // (8)
            startPromise.complete();
          });
        })
      );
    });

  }
}
  1. Instantiate the proxy

  2. Let’s try the first beer 🍺

  3. Something went wrong during beer retrieval, fail the verticle start

  4. Drinking the first one 🍻

  5. Give me another one 🍺

  6. Drinking the second one 🍻

  7. Time to go home. Give me the bill

  8. Pay the bill

Running the application

To run the application deploy the BarmanVerticle and subsequently the DrunkVerticle

package io.vertx.howtos.ebservice;

import io.vertx.core.Vertx;

public class BeersApplication {

  public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();
    vertx.deployVerticle(new BarmanVerticle(), ar -> {
      System.out.println("The barman is ready to serve you");
      vertx.deployVerticle(new DrunkVerticle(), ar2 -> {
        vertx.close();
      });
    });
  }

}

You can run the application from:

  1. your IDE, by running the main method from the BeersApplication class, or

  2. with Maven: mvn compile exec:java

You should see something like this:

The barman is ready to serve you
Generated a new Beer! Sourpuss (American Malt Liquor)
My first beer is a Sourpuss (American Malt Liquor) and it costs 5
Generated a new Beer! Amateur Mountain IPA (American IPA)
My second beer is a Amateur Mountain IPA (American IPA) and it costs 2
My bill with the bar is 7
Removed debt of homer

Summary

This how-to explained to you:

  1. How to design and implement an Event Bus Service using Vert.x Service Proxy, and

  2. How to expose the service on the event bus, and

  3. How to use the service


Last published: 2021-03-29 00:46:22 +0000.