Random Message Processing Consumer for RabbitMQ

  • Share this:

Code introduction


This function creates a consumer that randomly processes messages from a specified queue. It uses the RMQ (RabbitMQ) library to connect to a RabbitMQ server and defines a callback function to handle received messages. The function randomly decides whether to acknowledge the receipt of messages.


Technology Stack : RMQ (RabbitMQ) library, Python's random module, pika (RMQ client for Python)

Code Type : The type of code

Code Difficulty :


                
                    
import random
import pika

def random_queue_consumer(queue_name):
    """
    This function sets up a consumer that randomly processes messages from a given queue.
    It uses the RMQ (RabbitMQ) library to connect to a RabbitMQ server and consume messages.
    """
    # Establish connection to RabbitMQ server
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    
    # Declare a queue
    channel.queue_declare(queue=queue_name)
    
    # Callback function to be called when a message is received
    def callback(ch, method, properties, body):
        print(f"Received message: {body}")
        if random.choice([True, False]):  # Randomly decide to acknowledge or not
            ch.basic_ack(delivery_tag=method.delivery_tag)
    
    # Start consuming messages from the queue
    channel.basic_consume(queue=queue_name, on_message_callback=callback)
    
    print(f"Waiting for messages in {queue_name}. To exit press CTRL+C")
    try:
        channel.start_consuming()
    except KeyboardInterrupt:
        print("Interrupted")
    finally:
        connection.close()