Chethan Shankara
Chethan Shankara

Reputation: 85

Is There way to find the queue is empty using rabbit-template

I have subscriber which collects the messages until reaches the specified limit and then pass collected messages to the processor to perform some operations. Code works fine, problem is subscriber waits Until it collects specified number messages. If we have lesser message program control will not pass to processor.

For example Lets say my chunk size is 100 and if I have 100 or multiple of 100 messages then program works fine But if I have messages < 100 or 150 some of messages are read by subscriber but they were never passed to processor. Is there way I can figure-out is that Queue is empty using rabbit template so that I can check that condition and break the loop

@RabbitListener(id="messageListener",queues = "#{rabbitMqConfig.getSubscriberQueueName()}",containerFactory="queueListenerContainer")
    public void receiveMessage(Message message, Channel channel, @Header("id") String messageId, 
            @Header("amqp_deliveryTag") Long deliveryTag) {

        LOGGER.info(" Message:"+ message.toString());
        if(messageList.size() < appConfig.getSubscriberChunkSize() ) {
            messageList.add(message);
            deliveryTagList.add(deliveryTag);
            if(messageList.size() == appConfig.getSubscriberChunkSize()) {
                LOGGER.info("------------- Calling Message processor --------------");
                Message [] messageArry = new Message[messageList.size()];
                messageArry =  messageList.toArray(messageArry);
                LOGGER.info("message Array Length: "+messageArry.length);
                messageProcessor.process(messageArry);
                messageList = new ArrayList<Message>(Arrays.asList(messageArry));
                LOGGER.info("message Array to List conversion Size: "+messageList.size());
                LOGGER.info("-------------- Completed Message processor -----------");
                eppQ2Publisher.sendMessages(messageList, channel, deliveryTagList);
                messageList.clear();
                deliveryTagList.clear();
            }

        } else {
            // do nothing.. 

        }

Upvotes: 2

Views: 2339

Answers (2)

Ondřej Stašek
Ondřej Stašek

Reputation: 859

You can use RabbitAdmin.getQueueInfo("queue name").getMessageCount() that will be 0 for empty queue.

Upvotes: 0

Gary Russell
Gary Russell

Reputation: 174554

There are two ways to achieve this.

  1. Add an @EventListener to listen for ListenerContainerIdleEvents which are published when no messages have been received for some time; set the container's idleEventInterval property. The source of the event is the listener container; it contains the @RabbitListener's id. See Detecting Idle Consumers.

  2. Use RabbitAdmin.getQueueProperties().

Upvotes: 1

Related Questions