python-docker-sample/producer/app.py

91 lines
2.5 KiB
Python

#!/usr/bin/env python3
import pika
import json
import time
import os
import logging
from datetime import datetime
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("producer")
# RabbitMQ connection parameters
RABBITMQ_HOST = os.getenv("RABBITMQ_HOST", "rabbitmq")
RABBITMQ_PORT = int(os.getenv("RABBITMQ_PORT", "5672"))
RABBITMQ_USER = os.getenv("RABBITMQ_USER", "guest")
RABBITMQ_PASS = os.getenv("RABBITMQ_PASS", "guest")
QUEUE_NAME = os.getenv("QUEUE_NAME", "task_queue")
def connect_to_rabbitmq():
"""Establish connection to RabbitMQ with retry logic"""
while True:
try:
credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASS)
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host=RABBITMQ_HOST,
port=RABBITMQ_PORT,
credentials=credentials,
heartbeat=600,
)
)
logger.info("Connected to RabbitMQ successfully")
return connection
except pika.exceptions.AMQPConnectionError:
logger.warning("Failed to connect to RabbitMQ. Retrying in 5 seconds...")
time.sleep(5)
def publish_message(channel, task_id, task_data):
"""Publish a message to the queue"""
message = {
"task_id": task_id,
"timestamp": datetime.now().isoformat(),
"data": task_data,
}
channel.basic_publish(
exchange="",
routing_key=QUEUE_NAME,
body=json.dumps(message),
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
),
)
logger.info(f"Sent task {task_id}")
def main():
"""Main function that sends a message every few seconds"""
connection = connect_to_rabbitmq()
channel = connection.channel()
# Declare a queue (creates if doesn't exist)
channel.queue_declare(queue=QUEUE_NAME, durable=True)
task_id = 0
try:
while True:
task_id += 1
task_data = f"Task data for task {task_id}"
publish_message(channel, task_id, task_data)
# Wait before sending the next message
time.sleep(5)
except KeyboardInterrupt:
logger.info("Producer stopping due to keyboard interrupt")
finally:
connection.close()
logger.info("Connection to RabbitMQ closed")
if __name__ == "__main__":
logger.info("Producer service starting...")
main()