Setting up RabbitMQ, basics

This commit is contained in:
jetli 2024-10-12 09:10:13 -07:00
commit 9defc78732
5 changed files with 81 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.venv/

15
Dockerfile Normal file
View File

@ -0,0 +1,15 @@
# Dockerfile for Python Service
FROM python:3.11-slim
# Set working directory
WORKDIR /app
# Copy requirements file and install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt && rm -rf /root/.cache/pip
# Copy application code
COPY . .
# Run the Python script
CMD ["python", "main.py"]

32
docker-compose.yaml Normal file
View File

@ -0,0 +1,32 @@
version: '3.8'
services:
rabbitmq:
image: rabbitmq:3-management
ports:
- "5672:5672" # RabbitMQ communication port
- "15672:15672" # RabbitMQ management port
networks:
- rabbitmq_network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:15672"]
interval: 30s
retries: 5
start_period: 10s
timeout: 10s
python_service:
build:
context: .
dockerfile: Dockerfile
depends_on:
rabbitmq:
condition: service_healthy
environment:
RABBITMQ_HOST: rabbitmq
networks:
- rabbitmq_network
networks:
rabbitmq_network:
driver: bridge

32
main.py Normal file
View File

@ -0,0 +1,32 @@
import pika
import os
import time
# Environment variable for RabbitMQ connection
rabbitmq_host = os.getenv("RABBITMQ_HOST", "localhost")
def main():
# Establish a connection to RabbitMQ
connection = pika.BlockingConnection(pika.ConnectionParameters(host=rabbitmq_host))
channel = connection.channel()
# Declare a queue to ensure it exists
channel.queue_declare(queue='test_queue')
# Send a test message
message = "Hello, RabbitMQ!"
channel.basic_publish(exchange='', routing_key='test_queue', body=message)
print(f" [x] Sent '{message}'")
# Close the connection
connection.close()
if __name__ == "__main__":
# Adding a retry mechanism for RabbitMQ connection in case it isn't ready
for _ in range(5):
try:
main()
break
except pika.exceptions.AMQPConnectionError:
print("RabbitMQ not ready, retrying in 5 seconds...")
time.sleep(5)

1
requirements.txt Normal file
View File

@ -0,0 +1 @@
pika==1.3.2