I'm working with RabbitMQ and Java. I have an executeLogin() method, which sends a message on a queue and wait a reply on another queue: if the returned message contains true in the isSuccess field, I need to return true to the caller of the executeLogin() method, if isSuccess is false, i need to return false (not logged). I tried this way:
boolean logged = false;
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String message = new String(body, "UTF-8");
LoginConfirmation confirm = gson.fromJson(message, LoginConfirmation.class);
channel.queueDelete(reply_to);
System.out.println(" [x] Received '" + message + "'");
LOGGER.log(Level.FINE, gson.toJson(confirm));
logged = confirm.isSuccess();
}
};
channel.basicConsume(reply_to, true, consumer);
or this way:
GetResponse response = channel.basicGet(reply_to, false);
if(response == null){
System.out.println("No message");
}else{
byte[] body = response.getBody();
String msg = new String(body, "UTF-8");
System.out.println(msg);
}
But in both ways, I can't solve my problem: in the first way, it returns false, but it prints the message (with "isSuccess": true). In the second way, it prints "no message".
I think the problem is that basicConsume and defaultConsumer are asynchronous , so at the beginning it doesn't retrieve the message, but when it retrieves it, it prints it.
Yes, the communication is asynchronous.
In you case, I think, the RPC
pattern is appropriate:
https://www.rabbitmq.com/tutorials/tutorial-six-java.html
But what if we need to run a function on a remote computer and wait for the result? Well, that's a different story. This pattern is commonly known as Remote Procedure Call or RPC.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.