Dragos Roban
Dragos Roban

Reputation: 599

Synchronous EventBus message send in Vertx

I want to send multiple messages via EventBus in Vertx synchronously. I want to send a message, wait for it, and then send the next ones as well. The address is the same. If it's by default, how I do it? Or is it necessary to use executeBlocking code?

Here is my code.

public class EventBusSync {
    private Vertx vertx = Vertx.vertx();
    private static final String SERVICE_ADDRESS =  "service.worker";
    
  public void sentViaEvBus() {
    String message1 = "message1";
    String message2 = "message2";
    
    String reply1 = sendCommand(SERVICE_ADDRESS,message1);
    String reply2 = sendCommand(SERVICE_ADDRESS,message2);

  }

  private String sendCommand(String address, String command) {
   String message;
   vertx.eventBus().send(address,command, handler -> {
    if(handler.succeeded()) {
     log.info("success");
   } else {
     log.error("error",handler.cause());
     throw new RuntimeException("ERROR");
    }
    message = handler.result.body();
    });
 return message;
  }
 }

So here, if the first command is sent and something is happening, I want to interrupt the next eventbus' send.

Thanks

Upvotes: 0

Views: 3081

Answers (3)

Daniel P.
Daniel P.

Reputation: 369

The EventBus is made for asynchronous message passing (Publish / subscribe messaging, Point to point and Request-Response messaging). It does not make sense to force synchronous action.

If you want a synchronous response, simply call a method in another java class if you are in the same JVM.

Upvotes: 0

tsegismont
tsegismont

Reputation: 9128

Use CompleteFuture

  private String sendCommand(String address, String command) {
    CompletableFuture<String> completableFuture = new CompletableFuture<>();
    vertx.eventBus().<String>send(address, command, asyncResult -> {
      if (asyncResult.succeeded()) {
        completableFuture.complete(asyncResult.result().body());
      } else {
        completableFuture.completeExceptionally(asyncResult.cause());
      }
    });
    try {
      return completableFuture.get();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

Make sure though this code is not invoked on a Vert.x event loop, because get() will block until the reply is known.

Upvotes: 6

m4gic
m4gic

Reputation: 1513

Vert.x-sync examples

Here you will find examples demonstrating Vert.x-Sync in action.

[...]

This demonstrates using awaitResult to get send event bus messages and get the reply back, synchronously.

Upvotes: 0

Related Questions