同步事件总线消息在 Vertx 中发送



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

这是我的代码。

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()将阻塞,直到知道回复。

Vert.x-sync 示例

在这里,您将找到演示 Vert.x-Sync 运行的示例。

[...]

这演示了使用 等待结果 以同步获取发送事件总线消息并获取回复。

EventBus用于异步消息传递(发布/订阅消息传递、点对点和请求-响应消息传递(。强制同步操作是没有意义的。

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

最新更新