[英]Synchronous EventBus message send in Vertx
I want to send multiple messages via EventBus in Vertx but synchronous. 我想通过Vertx中的EventBus发送多个消息,但是是同步的。 I want to send a message, wait for it, and sent the next ones as well.
我想发送一条消息,等待它,并发送下一条消息。 The address it's the same.
地址是一样的。 It's by default how i do it?
默认情况下,我该怎么做? or it's necessary to use, maybe, an executeBlocking code?
还是有必要使用executeBlocking代码?
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 it's sent and something it's happening I want to interrupt the next eventbus sending. 所以在这里,如果第一个命令已发送并且正在发生某些事情,我想中断下一个事件总线的发送。
Thanks 谢谢
Use CompleteFuture
使用
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. 确保虽然未在Vert.x事件循环上调用此代码,因为
get()
将阻塞直到知道答复为止。
Vert.x-sync examples Vert.x同步示例
Here you will find examples demonstrating Vert.x-Sync in action.
在这里,您将找到演示Vert.x-Sync实际操作的示例。
[...]
[...]
This demonstrates using awaitResult to get send event bus messages and get the reply back, synchronously.
这演示了如何使用awaitResult来获取发送事件总线消息并同步返回答复。
The EventBus
is made for asynchronous message passing (Publish / subscribe messaging, Point to point and Request-Response messaging). EventBus
用于异步消息传递(发布/订阅消息传递,点对点和请求-响应消息传递)。 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. 如果要同步响应,如果您在同一JVM中,则只需在另一个Java类中调用一个方法即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.