Generate Random Queue ID with RabbitMQ

  • Share this:

Code introduction


This function connects to a RabbitMQ server, declares a queue, binds it to a routing key, then generates a random queue ID and sends a message containing this ID to the queue.


Technology Stack : RabbitMQ, pika

Code Type : Function

Code Difficulty : Intermediate


                
                    
def generate_random_queue_id(queue_name, routing_key):
    import random
    import pika
    
    # Connect to RabbitMQ server
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    
    # Declare a queue
    channel.queue_declare(queue=queue_name)
    
    # Generate a random queue ID
    random_queue_id = random.randint(1000, 9999)
    
    # Bind the queue to a routing key
    channel.queue_bind(exchange='', queue=queue_name, routing_key=routing_key)
    
    # Create a message with the random queue ID
    message = f"Queue ID: {random_queue_id}"
    
    # Publish the message to the queue
    channel.basic_publish(exchange='', routing_key=queue_name, body=message)
    
    # Close the connection
    connection.close()
    
    return random_queue_id                
              
Tags: