RabbitMQ Queue Connection and Consumption with Callback

  • Share this:

Code introduction


This function uses the RMQ (RabbitMQ Python Client) library to establish a connection to a local RabbitMQ server, declares a randomly named queue, defines a callback function to handle received messages, and starts consuming messages from the queue. When the user presses the keyboard interrupt key (usually Ctrl+C), it will stop consuming and close the connection.


Technology Stack : RMQ (RabbitMQ Python Client)

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random
import pika

def create_random_queue_connection():
    # Establish a connection to a RabbitMQ server
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    
    # Declare a random queue
    queue_name = 'random_queue_' + str(random.randint(1000, 9999))
    channel.queue_declare(queue=queue_name)
    
    # Define a callback function
    def callback(ch, method, properties, body):
        print(f"Received {body}")
    
    # Consume messages from the queue
    channel.basic_consume(queue=queue_name, on_message_callback=callback)
    
    # Start consuming messages
    print(f"Consuming from {queue_name}")
    try:
        channel.start_consuming()
    except KeyboardInterrupt:
        channel.stop_consuming()
    finally:
        connection.close()