java - Vertx 中同步发送 EventBus 消息

标签 java rx-java reactive-programming vert.x event-bus

我想通过 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;
  }
 }

因此,如果发送的第一个命令以及正在发生的事情,我想中断下一个事件总线发送。

谢谢

最佳答案

使用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);
    }
  }

确保此代码不会在 Vert.x 事件循环上调用,因为 get() 将阻塞,直到知道回复为止。

关于java - Vertx 中同步发送 EventBus 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52275322/

相关文章:

java - NoClassDefFoundError javax/jms/Message 即使在指定类路径时也是如此

JAVA - 从XML解析特定数据

android - 服务- fragment 通信

c++ - rxcpp 简单可观察<int>

angular - 如何在一系列 API 调用中正确链接可观察对象

java - react 堆项目 : Do I need a Processor?

java - 根据位置或项目在 ListView 中添加 View 时出错

java - 检测字符串是否只出现一次数字

android - Rx-java 是按引用传递还是按值传递?

java - Android Retrofit 从服务器下载/读取文本文件