Java - RabbitMQ consume some messages from a queue

Viewed 217

The scenario is that I want to consume a certain amount of messages from a queue, let's say 10, then produce the consumed messages to another queue. Basically, I want the shovel functionality, but I don't want to move all the messages at a time. For example lets say my queue has 100 messages I want to consume 10 of them and leave the other 90 in the queue.

Is this functionality possible without having to call channel.basicGet() 10 times in a row? How can I achieve such a thing using channel.basicConsume()

try {
    ConnectionFactory factory = new ConnectionFactory();
    // credentials
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.basicQos(10);

    final DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag,
                                   Envelope envelope,
                                   AMQP.BasicProperties properties,
                                   byte[] body)
            throws IOException {
            long deliveryTag = envelope.getDeliveryTag();
            // do some magic to prevent all the messages from being consumed
            channel.basicPublish("my-exchange", "my-routing-key", null, body);
            channel.basicAck(deliveryTag, false);
        }
    };

    channel.basicConsume(
        "my-queue",
        false,
        "my-consumer-tag",
        defaultConsumer);

} catch (Exception e) {
    e.printStackTrace();
}
0 Answers
Related