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
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read