RabbitMQ如何从java使用者返回消息
我正在使用RabbitMQ和Java。 我有一个executeLogin()方法,它在一个队列上发送消息,在另一个队列上等待答复:如果返回的消息在isSuccess字段中包含true,我需要将true返回给executeLogin()方法的调用方,如果isSuccess为false,我需要返回false(未记录)。 我试着这样做:RabbitMQ如何从java使用者返回消息,java,asynchronous,rabbitmq,Java,Asynchronous,Rabbitmq,我正在使用RabbitMQ和Java。 我有一个executeLogin()方法,它在一个队列上发送消息,在另一个队列上等待答复:如果返回的消息在isSuccess字段中包含true,我需要将true返回给executeLogin()方法的调用方,如果isSuccess为false,我需要返回false(未记录)。 我试着这样做: boolean logged = false; Consumer consumer = new DefaultConsumer(channel) { @Ov
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);
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);
}
或者这样:
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);
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);
}
但在这两方面,我都无法解决我的问题:
在第一种方式中,它返回false,但打印消息(带有“issucess”:true)。第二种方式是打印“无消息”
我认为问题在于basicConsume和defaultConsumer是异步的,因此在开始时它不会检索消息,但在检索时,它会打印消息。是的,通信是异步的 在您的情况下,我认为,
RPC
模式是合适的:
但是如果我们需要在远程计算机上运行一个函数并等待呢
结果如何?嗯,那是另一个故事。这种模式是
通常称为远程过程调用或RPC
是的,谢谢,但问题是我还没有意识到服务器组件,只有客户端。我发送一条消息,然后我必须在队列中等待一条消息,使用定义的路由密钥,分析该消息并向调用者返回一些信息。这可能吗?