Reputation: 313
I want to get all awaiting messages from a queue & then stop consumer. But it continues to wait for a new messages. I removed all unnecessary code:
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();
}
}
Upvotes: 2
Views: 3348
Reputation: 1409
nextDelivery()
without arguments just waits for a message when queue is empty. It shall never return null
. Instead you might be looking for nextDelivery(timeout) with a timeout. When time is out, the method will return null
.
You may also note that this method is deprecated, see RabbitMQ Java API Guide for a modern example.
Upvotes: 2