我希望得到所有等待来自队列的消息&然后停止消费者。但它继续等待新的消息。我删除了所有不必要的代码:
public class Listener {
private Channel channel;
public Listener(boolean futureActionsAllowed) {
this.futureActionsAllowed = futureActionsAllowed;
channel = RabbitMQ.getChannel(TasksStatusOpts.QUEUE_NAME, TasksStatusOpts.DURABLE, TasksStatusOpts.EXCLUSIVE,
TasksStatusOpts.AUTO_DELETE);
}
public void getAndExit() throws IOException, InterruptedException {
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
String consumerTag = channel.basicConsume(TasksStatusOpts.QUEUE_NAME, TasksStatusOpts.AUTO_ACK,
queueingConsumer);
while (true) {
QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
if (delivery == null) {
channel.basicCancel(consumerTag);
Connection conn = channel.getConnection();
channel.close();
conn.close();
break;
} else {
String message = new String(delivery.getBody(), Charsets.UTF_8);
handle(message, delivery.getEnvelope());
}
}
}
public static void main(String[] args) throws IOException {
new Listener(false).getAndExit();
}
}
答案 0 :(得分:1)
null
只在队列为空时等待消息。它永远不会返回null
。相反,您可能正在寻找超时的nextDelivery(timeout)。当时间结束时,该方法将返回Normal
。
您可能还注意到此方法已弃用,有关现代示例,请参阅RabbitMQ Java API Guide。