我有一个发送者和消费者交换消息:
public class Sender extends AbstractVerticle {
@Override
public void start() {
EventBus eventBus = vertx.eventBus();
eventBus.send(Constants.ADDRESS, "Hello from sender", res -> {
if (res.succeeded()) {
System.out.println("Successfully sent reply");
} else {
System.out.println("Failed to send reply." + res.cause());
}
});
eventBus.consumer(Constants.ADDRESS, msg -> System.out.println("received msg from consumer:" + msg.body()));
}
public class Consumer extends AbstractVerticle{
protected EventBus eventBus = null;
@Override
public void start() {
eventBus = vertx.eventBus();
eventBus.consumer(Constants.ADDRESS, msg -> msg.reply("Hi from consumer.", res -> {
if (res.succeeded()) {
System.out.println("Successfully sent reply");
} else {
System.out.println("Failed to send reply." + res.cause());
}
}));
}
}
我希望当消费者回复邮件时,发件人会收到邮件。但是,我得到了超时:
Successfully sent reply
Failed to send reply.(TIMEOUT,-1) Timed out after waiting 30000(ms) for a reply. address: 2, repliedAddress: 1
部署:
public class ServiceLauncher {
private static Vertx vertx = Vertx.vertx();
public static void main(String[] args) {
vertx.deployVerticle(new Consumer(), res -> {
if (res.succeeded()) {
System.out.println("Verticle " + Consumer.NAME + " deployed.");
vertx.deployVerticle(new Sender());
System.out.println("Verticle " + Sender.NAME + " deployed.");
} else {
System.out.println("Verticle " + Consumer.NAME + " not deployed.");
}
});
}
我做错了什么? Thanx提前
更新:问题在于msg.reply() - 消费者没有回复消息,但我仍然无法找出原因。
答案 0 :(得分:2)
超时不在请求的发件人中,而是在其收件人中。
msg.reply()
中定义的处理程序会等待发件人的下一次回复。它是不处理程序,只确认发送状态。
<{1}}的{{1}}中的处理程序也会在发件人收到回复时触发。
只需删除Sender
中的处理程序,然后以同样的方式修改eventBus.send()
中的处理程序msg.reply()
:
eventBus.send()
和
Sender
执行完毕后你会看到:
public class Sender extends AbstractVerticle {
public static final String NAME = "SENDER";
@Override
public void start() {
EventBus eventBus = vertx.eventBus();
eventBus.send(Constants.ADDRESS, "Hello from sender", res -> {
if (res.succeeded()) {
System.out.println("Successfully received reply: " + res.result().body());
} else {
System.out.println("Failed to send reply." + res.cause());
}
});
}
}
答案 1 :(得分:0)
我有一个类似的问题。就我而言,我正在发送非JsonObject答复。该消息必须使用有效的JsonObject进行回复,而不是JsonArray或其他任何东西。尽管文档没有提到JsonObject,但这看起来是默认行为。但是,原始代码段中的真正问题是您为回复的回复指定了处理程序。使用者已成功回复,但使用者未收到发件人的回复。请参阅下面的评论。
@Override
public void start() {
eventBus = vertx.eventBus();
eventBus.consumer(Constants.ADDRESS, msg -> msg.reply("Hi from consumer.", res -> {
if (res.succeeded()) { //this is expecting a response from Sender which never does so this will never execute.
System.out.println("Successfully sent reply");
} else { //it's not failing either so this will not execute either
System.out.println("Failed to send reply." + res.cause());
}
}));
}