#!/usr/bin/env python3 import pika import json import time import os import logging logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) logger = logging.getLogger("consumer") 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 process_message(task): """Process the received message""" logger.info(f"Processing task {task['task_id']}: {task['data']}") processing_time = 2 # seconds time.sleep(processing_time) logger.info(f"Completed task {task['task_id']} in {processing_time} seconds") def callback(ch, method, properties, body): """Callback function for message consumption""" try: task = json.loads(body) logger.info(f"Received task {task['task_id']} from {task['timestamp']}") # Process the message process_message(task) # Acknowledge the message (remove from queue) ch.basic_ack(delivery_tag=method.delivery_tag) except Exception as e: logger.error(f"Error processing message: {e}") # Reject the message and requeue ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True) def main(): """Main function that consumes messages from the queue""" # Connect to RabbitMQ connection = connect_to_rabbitmq() channel = connection.channel() # Declare the queue (creates if doesn't exist) channel.queue_declare(queue=QUEUE_NAME, durable=True) # Fair dispatch - don't give more than one message to a worker at a time channel.basic_qos(prefetch_count=1) # Set up the consumer channel.basic_consume(queue=QUEUE_NAME, on_message_callback=callback) logger.info("Consumer ready, waiting for messages...") try: # Start consuming messages channel.start_consuming() except KeyboardInterrupt: logger.info("Consumer stopping due to keyboard interrupt") channel.stop_consuming() finally: connection.close() logger.info("Connection to RabbitMQ closed") if __name__ == "__main__": logger.info("Consumer service starting...") main()