为了账号安全,请及时绑定邮箱和手机立即绑定

Vertx 中发送的同步 EventBus 消息

Vertx 中发送的同步 EventBus 消息

跃然一笑 2021-09-12 20:38:47
我想通过 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 发送。
查看完整描述

3 回答

?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

用 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()在知道答复之前会阻塞。


查看完整回答
反对 回复 2021-09-12
?
LEATH

TA贡献1936条经验 获得超6个赞

EventBus是为异步消息传递(发布/订阅消息,点对点和请求响应消息)制成。强制同步动作没有意义。

如果您想要同步响应,如果您在同一个 JVM 中,只需调用另一个 java 类中的方法。


查看完整回答
反对 回复 2021-09-12
?
森林海

TA贡献2011条经验 获得超2个赞

Vert.x-sync 示例

在这里,您将找到演示 Vert.x-Sync 实际应用的示例。

[...]

这演示了使用 awaitResult 来同步发送事件总线消息并获取回复。


查看完整回答
反对 回复 2021-09-12
  • 3 回答
  • 0 关注
  • 447 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号