Ilya
Ilya

Reputation: 313

How to get all existing messages from queue & stop consumer

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

Answers (1)

Alex Svetkin
Alex Svetkin

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

Related Questions