commit 9defc7873270d805ad6ae4e8cbc0ca3785f3983d Author: Jet Li Date: Sat Oct 12 09:10:13 2024 -0700 Setting up RabbitMQ, basics diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..21d0b89 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.venv/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a527cf6 --- /dev/null +++ b/Dockerfile @@ -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"] \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..ec341b2 --- /dev/null +++ b/docker-compose.yaml @@ -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 \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..1adeaf5 --- /dev/null +++ b/main.py @@ -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) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..cde8834 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +pika==1.3.2 \ No newline at end of file