已解决:移动
channel.basicPublish("",QUEUE,props,message.getBytes());
以下
channel.basicConsume(replyQueue,...)
解决了这个问题。
我试图弄清楚如何使用RabbitMQ直接回复功能。由于documentation在如何实现它方面相当模糊,我尝试使用RPC示例,将其用于直接回复。
private final static String QUEUE = "Test_chan";
private void directReplyToClient(ConnectionFactory factory) {
Connection connection = null;
Channel channel = null;
String replyQueue;
try {
connection = factory.newConnection();
channel = connection.createChannel();
//replyQueue = channel.queueDeclare().getQueue();
replyQueue = "amq.rabbitmq.reply-to";
AMQP.BasicProperties props = new AMQP.BasicProperties
.Builder()
.replyTo(replyQueue)
.build();
String message = "Hello World";
channel.basicPublish("", QUEUE, props, message.getBytes());
final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);
channel.basicConsume(replyQueue, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws UnsupportedEncodingException {
response.offer(new String(body, "UTF-8"));
}
});
System.out.println(response.take());
} catch (IOException | TimeoutException | InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (channel != null)
channel.close();
if (connection != null)
connection.close();
} catch (IOException | TimeoutException _ignore) {}
}
}
将回复地址设为
channel.queueDeclare()。getQueue()
有效,但设置为
amq.rabbitmq.reply到
给出以下例外:
线程中的异常&#34; main&#34; com.rabbitmq.client.AlreadyClosedException: 由于频道错误,频道已经关闭;协议方法: 方法(reply-code = 406,reply-text = PRECONDITION_FAILED - 快速回复消费者不存在,class-id = 60,method-id = 40)
有谁看到我做错了什么?任何指针都将受到赞赏。
答案 0 :(得分:3)
所以这是解决方案的代码。在发布之前进行消费。
private final static String QUEUE = "Test_chan";
private void directReplyToProducer(ConnectionFactory factory) {
Connection connection = null;
Channel channel = null;
String replyQueue;
try {
connection = factory.newConnection();
channel = connection.createChannel();
replyQueue = "amq.rabbitmq.reply-to";
AMQP.BasicProperties props = new AMQP.BasicProperties
.Builder()
.replyTo(replyQueue)
.build();
String message = "Hello World";
final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);
System.out.println(" [x] Sent x'" + message + "'");
channel.basicConsume(replyQueue, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws UnsupportedEncodingException {
response.offer(new String(body, "UTF-8"));
}
});
channel.basicPublish("", QUEUE, props, message.getBytes());
System.out.println(response.take());
Thread.sleep(10000);
} catch (IOException | TimeoutException | InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (channel != null)
channel.close();
if (connection != null)
connection.close();
} catch (IOException | TimeoutException _ignore) {}
}
}