我使用EventBus发送消息,我想将回复消息发送到变量中,然后返回它。这是代码块。
public class MessageExecute {
private static final Logger logger = LoggerFactory.getLogger(MessageExecute.class);
public static <T> T sendMessage(Vertx vertx,String address,T message){
Future<Message<T>> future = Future.future();
vertx.eventBus().send(address, message, future.completer());
future.setHandler(new Handler<AsyncResult<Message<T>>>() {
@Override
public void handle(AsyncResult<Message<T>> event) {
logger.info("received reply message | thread - " + Thread.currentThread().getName());
}
});
boolean notFound = true;
while(notFound){
try{
if(future.result()!= null){
notFound = false;
}
}catch(Exception e){
}
}
return message;
}
}
实际上这个工作正常。但有些时候虽然块永远不会退出。它意味着future.result()没有得到价值,即使收到回复消息后。我不知道这是正确的方式而且我不知道我们清楚地了解期货如何在vert.x中运作。是否有其他方法可以实现这种情况。
答案 0 :(得分:1)
我建议您阅读Vertx-Sync项目 - http://vertx.io/docs/vertx-sync/java/
在示例中,让以下示例与您的案例非常相似:
EventBus eb = vertx.eventBus();
HandlerReceiverAdaptor<Message<String>> adaptor = streamAdaptor();
eb.<String>consumer("some-address").handler(adaptor);
// Receive 10 messages from the consumer:
for (int i = 0; i < 10; i++) {
Message<String> received1 = adaptor.receive();
System.out.println("got message: " + received1.body());
}