Hot questions for Using EventBus in vert.x

Question:

My case is:

  • single JVM
  • Java only (i don't need to be polyglot)
  • I don't want to pay serialization costs to publish an immutable event on the bus (publishing the reference to the java object would work).

I understand the scope of the vert.x event bus is much broader than my use case.

I had in mind a behaviour similar to akka: when you go distributed you have to provide serialization for your messages, if you stay local references get passed.

Is there anything that would allow me to do that in Vert.x?


Answer:

Vert.x already has such an optimization. When sending to the same JVM, objects won't get serialized or deserialized.

You can see the actual code here: https://github.com/eclipse/vert.x/blob/master/src/main/java/io/vertx/core/eventbus/impl/EventBusImpl.java#L372

When you implement your MessageCodec, you actually have two methods: decodeFromWire() and transform(). You can implement only transform with the most naive approach:

@Override
public Object transform(Object o) {
   return o;
}

Question:

guys!

While using Vert.x, I found I cannot get the result out of EventBus while communicating with other Verticle.

class Result<T> {
    public T value;
    public String message;
    // ...
}

private Result<Integer> someMethod() {
        try {
            var json = new JsonObject();
            vertx.eventBus().<JsonObject>send(Service.EVENT_BUS_ADDRESS, json, ar -> {
                if (ar.succeeded()) {
                    var result = new Result<List>(ar.result().body());
                    if (result.isSuccessful()) {
                        Result.succeed(result);
                    } else {
                        Result.fail(result.message);
                    }
                } else {
                    Result.fail("Remote server error");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
        return // how can I return the result in EventBus???
    }

So how can I get the value out of the Async block and return it?


Answer:

You shouldn't return the result but notify a handler instead

The following code assumes your Result.succeeed or Result.fail method return an instance of Result

private void someMethod(Handler<Result> resultHandler) {
  ...
  vertx.eventBus().<JsonObject>send(Service.EVENT_BUS_ADDRESS, json, ar -> {
            if (ar.succeeded()) {
                var result = new Result<List>(ar.result().body());
                if (result.isSuccessful()) {
                    resultHandler.handle(Result.succeed(result));
                } else {
                    resultHandler.handle(Result.fail(result.message));
                }
            } else {
                resultHandler.handle(Result.fail("Remote server error"));
            }
  ...
}