Integrating RabbitMQ with Python
Last Updated :
28 Jun, 2024
In this article, we will guide you through setting up and using RabbitMQ with Python. RabbitMQ is a powerful message broker that allows applications to communicate with each other via messages. This practical guide will show you how to connect to RabbitMQ, publish messages to a queue, and consume messages from a queue using Python. Additionally, we will use Docker to manage RabbitMQ in a containerized environment, ensuring a smooth and isolated setup. Whether you are new to message brokers or looking to integrate RabbitMQ into your Python projects, this guide will provide you with a solid foundation to get started.
Environment Setup - How to Use RabbitMQ with Python?
To get started, follow these steps to set up your development environment:
1. Create and activate the virtual environment
Creating a virtual environment helps to isolate your project’s dependencies. Here’s how you can create and activate a virtual environment:
2. Install the dependencies
Next, install the required Python packages. For this project, we will use the pika library to interact with RabbitMQ.
Install the required packages:
pip install pika
Installed packages to requirements.txt:
pip freeze > requirements.txt
With the environment set up and dependencies installed, you’re ready to move on to the next steps in configuring RabbitMQ with Docker.
Docker Setup
In this section, we will configure and start RabbitMQ using Docker. This allows us to easily manage and isolate RabbitMQ in a containerized environment.
1. Create a `docker-compose.yaml` file
Create a file named `docker-compose.yaml` in the root of your project directory.
- Add the following content to the file:
version: '3.8'
services:
rabbitmq:
image: rabbitmq:3-management
container_name: rabbitmq
ports:
- '5672:5672'
- '15672:15672'
environment:
RABBITMQ_DEFAULT_USER: guest
RABBITMQ_DEFAULT_PASS: guest
This configuration sets up RabbitMQ with the management plugin enabled, allowing you to access the RabbitMQ management console on port 15672.
2. Start the RabbitMQ container
- Run the following command to build and start the RabbitMQ container:
docker-compose up -d
This command will download the RabbitMQ Docker image (if not already available locally), start the container, and run it in the background. The RabbitMQ server will be accessible at localhost:5672, and the management console will be available at http://localhost:15672.
With RabbitMQ running in a Docker container, you are ready to move on to the next steps of developing the application and integrating RabbitMQ with your Python code.
Application Development
In this section, we will develop the application that connects to RabbitMQ, publishes messages to a queue, and consumes messages from a queue. We’ll start by implementing a class to manage the connection and interactions with RabbitMQ.
1. Implement the RabbitMQ class
Create a file named `rabbitmq.py` in the root of your project directory.
Python
import pika
import os
class RabbitMQ:
def __init__(self):
self.user = os.getenv('RABBITMQ_USER', 'user')
self.password = os.getenv('RABBITMQ_PASSWORD', 'password')
self.host = os.getenv('RABBITMQ_HOST', 'localhost')
self.port = int(os.getenv('RABBITMQ_PORT', 5672))
self.connection = None
self.channel = None
self.connect()
def connect(self):
credentials = pika.PlainCredentials(self.user, self.password)
parameters = pika.ConnectionParameters(host=self.host, port=self.port, credentials=credentials)
self.connection = pika.BlockingConnection(parameters)
self.channel = self.connection.channel()
def close(self):
if self.connection and not self.connection.is_closed:
self.connection.close()
def consume(self, queue_name, callback):
if not self.channel:
raise Exception("Connection is not established.")
self.channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
self.channel.start_consuming()
def publish(self, queue_name, message):
if not self.channel:
raise Exception("Connection is not established.")
self.channel.queue_declare(queue=queue_name, durable=True)
self.channel.basic_publish(exchange='',
routing_key=queue_name,
body=message,
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
))
print(f"Sent message to queue {queue_name}: {message}")
This class handles connecting to RabbitMQ, publishing messages to a queue, and consuming messages from a queue. The connection parameters are read from environment variables.
2. Create the main.py script
Create a file named `main.py` in the root of your project directory.
Python
from rabbitmq import RabbitMQ
def callback(ch, method, properties, body):
print(f"Received {body}")
rabbitmq = RabbitMQ()
rabbitmq.consume(callback)
This script connects to RabbitMQ and starts consuming messages from a queue named test_queue.
3. Create the publisher.py script
Create a file named `publisher.py` in the root of your project directory.
Python
from rabbitmq import RabbitMQ
rabbitmq = RabbitMQ()
message = 'Test message'
rabbitmq.publish(message)
print(f"Sent message: {message}")
rabbitmq.close()
This script publishes a test message to the test_queue.
With these scripts in place, you are ready to run and test your application.
Running the Application
In this section, we will run the application to ensure everything is set up correctly and that we can successfully publish and consume messages using RabbitMQ.
1. Start the RabbitMQ server
Run the `main.py` script to start the RabbitMQ server and begin consuming messages from the test_queue:
python main.py
You should see a message indicating that the connection to RabbitMQ was established successfully. The script will continue running and wait for messages to consume from the test_queue.
2. Publish a test message
Open a new terminal window or tab, and run the `publisher.py` script to publish a test message to the test_queue:
python publisher.py
You should see a message indicating that the test message was published successfully. The `main.py` script should also display the received message, indicating that the message was successfully consumed from the test_queue.
Example Output
When you run `main.py`, you should see something like this:
Connection to RabbitMQ established successfully.
Received message: 'Test message'
When you run `publisher.py`, you should see something like this:
Sent message to queue test_queue: Test message
Test message published successfully.
Conclusion
In this guide, we covered the steps to set up and use RabbitMQ with Python. We demonstrated how to configure the development environment, run RabbitMQ in a Docker container, and create a simple application to publish and consume messages. This should give you a solid foundation to start integrating RabbitMQ into your own projects.
Similar Reads
Automating Tasks with Python: Tips and Tricks
Python is a versatile and simple-to-learn programming language for all developers to implement any operations. It is an effective tool for automating monotonous operations while processing any environment. Programming's most fruitful use is an automation system to identify any process, and Python's
6 min read
Python - Asynchronous Task using RabbitMQ
Have you ever faced an issue where you need to perform a task in background that will take up a lot of time to complete? Have you ever wanted to perform a task after a certain interval of time? If your answer was "YES" for any of the above questions, then Python has got you covered. We will be demon
4 min read
Introduction to SQLite in Python
SQLite is a lightweight, fast and embedded SQL database engine. SQLite is perfect for small to medium-sized applications, prototyping, embedded systems and local data storage in Python applications because it doesn't require a separate server process like other relational database management systems
4 min read
PyVista and QT Integration
PyVista, a versatile Python library built on top of VTK (Visualization Toolkit), provides an easy-to-use interface for 3D visualization and mesh analysis. On the other hand, Qt, a powerful framework for building graphical user interfaces (GUIs), offers a wide range of tools for creating desktop appl
5 min read
How to Use Mega.nz API With Python?
In this article, we are going to see how to use mega.nz API with Python. MEGA.NZ is End-to-end encrypted and the encryption keys are owned by us. It means that mega.NZ employees won't be able to read personal data. Mega.py is a great Python module for interacting with mega.nz API. It provides easy t
3 min read
Python | Getting started with SymPy module
SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python. SymPy only depends on mpmath, a pure Python libra
4 min read
Getting Started with Pytest
Python Pytest is a framework based on Python. It is mainly used to write API test cases. It helps you write better programs. In the present days of REST services, Pytest is mainly used for API testing even though we can use Pytest to write simple to complex test cases, i.e., we can write codes to te
5 min read
Python | sympy.integrate() method
With the help of sympy.integrate() method, we can find the integration of mathematical expressions in the form of variables by using sympy.integrate() method. Syntax : sympy.integrate(expression, reference variable) Return : Return integration of mathematical expression. Example #1 : In this example
1 min read
Python MySQL - Insert into Table
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify
3 min read
Bulk insert with SQLAlchemy ORM in Python
In this article, we will see how to insert or add bulk data using SQLAlchemy in Python. SQLAlchemy is among one of the best libraries to establish communication between python and databases. We have used the PostgreSQL database for this article. Create a database for demonstration: CREATE DATABASE T
1 min read