Search code examples
javarabbitmqmessagingamqp

RabbitMQ Prefetch Ignored


I'm running into a problem where setting basic.qos to 1 doesn't have the desired effect - tons of messages are still pushed to my consumer.

My code looks a little something like this:

    Channel channel = getChannel("pollQueuePassive"); // from our own channel pool implementation

    try{
        channel.queueDeclarePassive(queue.name);
    } catch (IOException e){
        channel = getChannel("pollQueueActive");
        channel.queueDeclare(queue.name, true, false, false, null);
    }

    channel.basicQos(1);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queue.name, autoAck, consumer);

    while (!stopPolling()) { 
        try{
              QueueingConsumer.Delivery delivery = consumer.nextDelivery();
              String message = new String(delivery.getBody());

              boolean workResult = doWork(message);
              if(!autoAck) {
                  if(workResult) 
                      channel.basicAck(delivery.getEnvelope().getDeliveryTag(), true);
                  else
                      channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, true);
              }

            } catch (InterruptedException e) {}
    }

    closeConnection();

As soon as I begin to a consume from a queue in this way, all messages in the queue (upwards of 20,000, in some cases) are almost instantly delivered to the consumer. Since I'd like to distribute the messages in the queue to dozens of consumers simultaneously, this behavior is obviously undesirable. I've played with moving my basic.qos declaration around - including immediately before returning the channel from our channel pool - to no avail. Any ideas why the prefetch size wouldn't be honored?

Thanks!


Solution

  • From official doc:

    The prefetch-count is ignored if the no-ack option is set.

    and looks like you are using auto-ack flag for your consumer. To be sure check the value of autoAck variable.