The event bus is a distributed messaging system that allows verticles and other components to exchange messages. The event bus supports point-to-point, publish-subscribe, and request-response patterns, and can handle different types of messages, such as JSON, buffers, strings, and custom objects. To use the event bus, you need to use the Vertx.eventBus method, which returns an EventBus instance. You can then use the send, publish, request, or consumer methods to send or receive messages. For example, you can create a verticle that sends a JSON message to the address "hello" every second, and another verticle that consumes the message and prints it:
public class SenderVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
vertx.setPeriodic(1000, id -> {
JsonObject message = new JsonObject().put("name", "Vert.x");
vertx.eventBus().send("hello", message);
});
}
}
public class ReceiverVerticle extends AbstractVerticle {
@Override
public void start() throws Exception {
vertx.eventBus().consumer("hello", message -> {
System.out.println("Received: " + message.body());
});
}
}