0
0
RabbitmqHow-ToBeginner ยท 3 min read

How to Consume Messages from RabbitMQ: Simple Guide

To consume messages from RabbitMQ, you create a consumer that connects to the queue and listens for messages using a callback function. Use basic_consume to register the callback and start_consuming to begin receiving messages.
๐Ÿ“

Syntax

To consume messages from RabbitMQ, you use these main steps:

  • channel.basic_consume(queue, on_message_callback): Registers a function to handle incoming messages from the specified queue.
  • channel.start_consuming(): Starts the loop that waits for messages and calls the callback when a message arrives.
  • on_message_callback(ch, method, properties, body): Your function that processes each message.
python
channel.basic_consume(queue='queue_name', on_message_callback=callback_function)
channel.start_consuming()
๐Ÿ’ป

Example

This example shows how to connect to RabbitMQ, consume messages from a queue named hello, and print each message received.

python
import pika

def callback(ch, method, properties, body):
    print(f"Received message: {body.decode()}")

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)

print('Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
Output
Waiting for messages. To exit press CTRL+C Received message: Hello World!
โš ๏ธ

Common Pitfalls

Common mistakes when consuming messages from RabbitMQ include:

  • Not calling start_consuming(), so the consumer never listens for messages.
  • Forgetting to acknowledge messages if auto_ack is set to False, causing messages to remain unacknowledged.
  • Not declaring the queue before consuming, which can cause errors if the queue does not exist.
  • Blocking the callback function with long processing, which delays message handling.
python
# Wrong way (missing start_consuming):
channel.basic_consume(queue='hello', on_message_callback=callback)
# No start_consuming() call

# Right way:
channel.basic_consume(queue='hello', on_message_callback=callback)
channel.start_consuming()
๐Ÿ“Š

Quick Reference

CommandDescription
queue_declare(queue)Create or check a queue exists
basic_consume(queue, callback)Register callback to receive messages
start_consuming()Start waiting and processing messages
auto_ack=True/FalseAutomatically acknowledge messages or manual ack
basic_ack(delivery_tag)Manually acknowledge a message
โœ…

Key Takeaways

Use basic_consume with a callback function to receive messages from a queue.
Always call start_consuming() to begin listening for messages.
Declare the queue before consuming to avoid errors.
Set auto_ack=True to auto-acknowledge or manually acknowledge messages to prevent re-delivery.
Keep the callback function fast to avoid blocking message processing.