The Event Bus

The event-bus is the nervous system of Vert.x.There is a single event bus instance for every Vert.x instance and it is obtained using the method event-bus.

Sending Message

Messages are sent on the event bus to an address. Out of the box Vert.x allows any primitive/simple type, String, or buffers to be sent as messages. The event bus is very flexible and also supports sending arbitrary objects over the event bus. You can do this by defining a codec for the objects you want to send.

Message Codec

message codec allows a custom message type to be marshalled across the event bus. Usually the event bus only allows a certain set of message types to be sent across the event bus, including primitive types, boxed primitive types, byte[], JsonObject, JsonArray, Buffer. By specifying a message codec you can pass any other type across the event bus, e.g. POJOs. With a message codec the type sent does not have to be the same as the type received, e.g. you could send a Buffer and have it be received as a JsonObject. Instances of this class must be thread-safe as they may be used concurrently by different threads.

Generic Codec

The Generic codec provide a simple way to send any object in the event-bus by using java object serialization.

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and de-serialized on an entirely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and de-serializing an object.

By adding java serialization to Vert.x MessageCodec we can get a GenericCodec that can decode/encode any java object:

This codec Behaving differently in case of sending message in same process and in case of sending message to a different process.

If we using this codec to send message in same process, The object will send with same reference, This means that the object is not thread-safe, but when we send to verticle in other process the codec will use java serialization to send it.

Example how to use it?

Register to codec with class:

vertx.eventBus().registerDefaultCodec(SomeClass.class,
      new GenericCodec<SomeClass>(SomeClass.class));

Sending Object:

SomeClass object;
vertx.eventBus().publish("some topic", object);

Consume Event with Generic Codec:

vertx.eventBus().consumer(“some topic”, context -> {
      SomeClass msg = (SomeClass) context.body();
      //do something with the object
 });

Summary

We saw a simple way to send any Java object with GenericCodec. In this example we used java object serialization to serialize objects, But we can use any other way to serialize object like json or xml.