关于rabbitmq收不到消息的问题
来源:3-13 完善骑手微服务
要加油啊1232129
2022-02-08
请问老师在handlerMessage()方法中,while语句写在try块里面就可以正常收到消息,写在try外面就收不到消息,这是什么原因?
@Async
public void handleMessage() throws IOException, TimeoutException, InterruptedException {
log.info("settlement开始监听消息队列");
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("localhost");
try (Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();){
channel.exchangeDeclare("exchange.order.settlement", BuiltinExchangeType.FANOUT,
true,false, null);
channel.queueDeclare("queue.settlement", true, false, false, null);
channel.queueBind("queue.settlement", "exchange.order.settlement", "key.settlement");
channel.basicConsume("queue.settlement",true,deliverCallback,consumerTag->{
});
while (true) {
Thread.sleep(1000000);
}
}
}
此时可以正常收到消息。
个人分析原因:
在try块中的语句执行完毕之后,rabbitmq的连接被关闭了
请老师指点!
还有就是这个死循环线程休眠这里的代码,我还不是很理解,希望老师能详细地说明一下,谢谢老师!
写回答
1回答
-
Moody
2022-02-08
1这里使用了Java的“try with resource”特性,try后面的括号新建了连接。出了try块,连接会被自动关闭。
2 这个地方休眠在这里应该也是为了不出try块,没有特别的其他意义的。后面使用spring的AMQP包之后,这种做法就不需要了~
00
相似问题