Python: how to use RabbitMQ

Python: how to use RabbitMQ

In this article, we will explore how to use RabbitMQ in Python to facilitate communication between different parts of a distributed system.

RabbitMQ is an open-source message broker widely used for managing message queues in distributed applications. In this article, we will explore how to use RabbitMQ in Python to facilitate communication between different parts of a distributed system.

The Pika client for Python

Once RabbitMQ is installed, it will be useful to use a Python client to interact with the message broker. One of the most popular clients is pika. Let's install it using the pip:

package manager

pip install pika

Connecting to RabbitMQ


import pika

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

In the code above, we connect to RabbitMQ on the local machine. Make sure to change the connection address and credentials if RabbitMQ is running on a remote server or if you have configured users and passwords.

Creating an exchange and a queue


# Declaration of a 'direct' exchange
channel.exchange_declare(exchange='direct_exchange', exchange_type='direct')

# Declaring a queue
channel.queue_declare(queue='my_queue')

# Connecting the queue to the exchange with a routing key
channel.queue_bind(exchange='direct_exchange', queue='my_queue', routing_key='routing_key')

In the code above, we have declared a direct exchange called direct_exchange and a queue called my_queue. Next, we connected the queue to the exchange using a routing key.

Sending a message


# Sending a message to the exchange with a routing key
channel.basic_publish(exchange='direct_exchange', routing_key='routing_key', body='Hello, RabbitMQ!')

Receiving a message


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

# Statement from a consumer using the callback function
channel.basic_consume(queue='my_queue', on_message_callback=callback, auto_ack=True)

# Consumer startup
channel.start_consuming()

In the code above, we have defined a callback function callback which is called when a message is received from the my_queue queue. Next, we declared a consumer and started consuming the messages.

Conclusions

This short guide provides a hands-on introduction to using RabbitMQ in Python. You can further experiment with different configurations of exchanges, queues, and routing keys to tailor RabbitMQ to the specific needs of your distributed system. The use of RabbitMQ allows you to improve the reliability and scalability of applications, allowing asynchronous and efficient communication between the different components.