0
0
RabbitmqHow-ToBeginner · 4 min read

How to Use RabbitMQ with Python: Simple Guide and Example

To use RabbitMQ with Python, install the pika library, then create a connection to RabbitMQ server, declare a queue, and send or receive messages using channels. Use pika.BlockingConnection for simple synchronous communication.
📐

Syntax

Here is the basic syntax to connect to RabbitMQ, declare a queue, and send a message using Python's pika library:

  • Connection: Establish connection to RabbitMQ server.
  • Channel: Create a channel to communicate.
  • Queue Declare: Declare the queue to send/receive messages.
  • Publish: Send a message to the queue.
  • Consume: Receive messages from the queue.
python
import pika

# Connect to RabbitMQ server
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

# Declare a queue
channel.queue_declare(queue='hello')

# Publish a message
channel.basic_publish(exchange='', routing_key='hello', body='Hello World!')

# Close connection
connection.close()
💻

Example

This example shows a simple Python script that sends a message to a RabbitMQ queue and another script that receives and prints the message.

python
# Sender (send.py)
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='', routing_key='hello', body='Hello RabbitMQ!')
print("[x] Sent 'Hello RabbitMQ!'")
connection.close()


# Receiver (receive.py)
import pika

def callback(ch, method, properties, body):
    print(f"[x] Received {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
[x] Sent 'Hello RabbitMQ!' # When running receive.py: [*] Waiting for messages. To exit press CTRL+C [x] Received Hello RabbitMQ!
⚠️

Common Pitfalls

  • Not declaring the queue before sending or receiving causes errors.
  • Forgetting to close connections can lead to resource leaks.
  • Using auto_ack=False without manual acknowledgment can cause message loss.
  • Not handling connection errors or server unavailability leads to crashes.

Always declare queues on both sender and receiver sides and handle exceptions.

python
import pika

# Wrong: Not declaring queue before publishing
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# channel.queue_declare(queue='hello')  # Missing queue declaration
channel.basic_publish(exchange='', routing_key='hello', body='Test')  # This may fail
connection.close()

# Right: Declare queue before publishing
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
channel.basic_publish(exchange='', routing_key='hello', body='Test')
connection.close()
📊

Quick Reference

Here is a quick summary of key pika methods for RabbitMQ in Python:

MethodPurpose
pika.BlockingConnection(parameters)Connect to RabbitMQ server
connection.channel()Create a channel for communication
channel.queue_declare(queue='name')Declare a queue
channel.basic_publish(exchange='', routing_key='queue', body='message')Send message to queue
channel.basic_consume(queue='name', on_message_callback=func, auto_ack=True)Receive messages with callback
channel.start_consuming()Start waiting for messages
connection.close()Close connection

Key Takeaways

Install pika library to use RabbitMQ with Python.
Always declare queues before sending or receiving messages.
Use BlockingConnection and channels for simple synchronous messaging.
Handle connection errors and close connections properly.
Use basic_consume with a callback to receive messages asynchronously.