猿问

Vertx 中发送的同步 EventBus 消息

我想通过 Vertx 中的 EventBus 但同步发送多条消息。我想发送一条消息,等待它,然后发送下一条消息。地址是一样的。默认情况下我是怎么做的?或者有必要使用,也许,一个 executeBlocking 代码?


这是我的代码。


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;

  }

 }

所以在这里,如果它发送了第一个命令并且正在发生某些事情,我想中断下一个 eventbus 发送。


跃然一笑
浏览 448回答 3
3回答

汪汪一只猫

用 CompleteFuture&nbsp; private String sendCommand(String address, String command) {&nbsp; &nbsp; CompletableFuture<String> completableFuture = new CompletableFuture<>();&nbsp; &nbsp; vertx.eventBus().<String>send(address, command, asyncResult -> {&nbsp; &nbsp; &nbsp; if (asyncResult.succeeded()) {&nbsp; &nbsp; &nbsp; &nbsp; completableFuture.complete(asyncResult.result().body());&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; completableFuture.completeExceptionally(asyncResult.cause());&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; return completableFuture.get();&nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; throw new RuntimeException(e);&nbsp; &nbsp; }&nbsp; }请确保此代码不会在 Vert.x 事件循环上调用,因为get()在知道答复之前会阻塞。

LEATH

的EventBus是为异步消息传递(发布/订阅消息,点对点和请求响应消息)制成。强制同步动作没有意义。如果您想要同步响应,如果您在同一个 JVM 中,只需调用另一个 java 类中的方法。

森林海

Vert.x-sync 示例在这里,您将找到演示 Vert.x-Sync 实际应用的示例。[...]这演示了使用&nbsp;awaitResult&nbsp;来同步发送事件总线消息并获取回复。
随时随地看视频慕课网APP

相关分类

Java
我要回答