How to stop consuming message from selective queue - RabbitMQ

user1182253 picture user1182253 · Apr 28, 2014 · Viewed 20.5k times · Source
QueueingConsumer consumer = new QueueingConsumer(channel);
System.out.println(consumer.getConsumerTag());
channel.basicConsume("queue1", consumer);
channel.basicConsume("queue3", consumer);

Is it possible to stop consuming the messages from the queue "queue3" alone dynamically?

Answer

Gabriele Santomaggio picture Gabriele Santomaggio · Apr 28, 2014

Yes you can, using channel.basicCancel(consumerTag); EDIT For example:

String tag3 = channel.basicConsume("queue3", consumer);
channel.basicCancel(tag3)

Here you can find a code that unsubscribe a consumer after 5 seconds:

String tag1 = channel.basicConsume(myQueue, autoAck, consumer);
String tag2 = channel.basicConsume(myQueue2, autoAck, consumer);
    executorService.execute(new Runnable() {
        @Override
        public void run() {
            while (true) {
                Delivery delivery;
                try {
                    delivery = consumer.nextDelivery();
                    String message = new String(delivery.getBody());
                    System.out.println("Received: " + message);
                } catch (Exception ex) {
                    Logger.getLogger(TestMng.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    });
    System.out.println("Consumers Ready");
    try {
        Thread.sleep(5000);
    } catch (InterruptedException ex) {
        Logger.getLogger(TestMng.class.getName()).log(Level.SEVERE, null, ex);
    }

    channel.basicCancel(tag2); /// here you remove only the Myqueue2

I hope it can be useful.