6

I have a RabbitMQ queue in which I post thousands of messages. I need a background Service that will:

  • Retrieve the messages in batches of 100 messages
  • Store those 100 messages in a Database
  • Ack all 100 messages at once
  • Proceed with the next batch of 100 messages

I'm using the RabbitMQ Client to listen for messages, but I don't know how to "batch" them.

Does anyone has a working example on how to get my messagess 100-100 at a time and ACK them all at once after they have been saved in a DB?

Thanx a lot in advance

Katia S.
  • 197
  • 2
  • 13

1 Answers1

8

You want to use the "prefetch" and "multi ack" features -

This is what you'll do in your code:

  • Open a connection and channel
  • Set the channel prefetch to 100
  • Start a consumer. The callback you register for your consumer will start being called with messages. You will have to save these messages in a list or other data structure
  • Once you have received 100 messages, save the delivery tag of the 100th message and do your database work.
  • Ack the 100 messages by setting "multi ack" to true and use the delivery tag of the 100th message.
  • RabbitMQ will send the next 100 messages in the same manner

NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.

Luke Bakken
  • 8,993
  • 2
  • 20
  • 33
  • StackOverflow's design lends itself to simple answers like the one given here. For anything in-depth, the format is not ideal, which is why we direct people to the mailing list - https://groups.google.com/forum/#!forum/rabbitmq-users – Luke Bakken May 23 '22 at 20:34
  • Is it possible that RabbitMQ stores the batches message and once hit the prefetch limit, send the batched messages to consumers? this way we don't need to store the received message in consumers one by one. – Shahin Ghasemi Dec 11 '22 at 08:05
  • @ShahinGhasemi that is not how the AMQP protocol works. There shouldn't be an issue with storing messages one at a time in the appropriate data structure. You may also wish to investigate RabbitMQ streams - https://www.rabbitmq.com/streams.html – Luke Bakken Dec 11 '22 at 16:15