Random Queue and Exchange Message Publishing to RabbitMQ

  • Share this:

Code introduction


This function connects to the local RabbitMQ server, declares a random queue and a random exchange, then sends a message with a random routing key to the exchange. Finally, it closes the connection.


Technology Stack : PyAMQP, RabbitMQ

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import pika
import json

def random_queue_message_exchanges():
    # Connect to the RabbitMQ server
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    
    # Declare a random queue
    queue_name = random.choice(['queue1', 'queue2', 'queue3'])
    channel.queue_declare(queue=queue_name)
    
    # Declare a random exchange
    exchange_name = random.choice(['exchange1', 'exchange2', 'exchange3'])
    channel.exchange_declare(exchange=exchange_name, exchange_type='direct')
    
    # Publish a random message to the exchange
    routing_key = random.choice(['key1', 'key2', 'key3'])
    message = json.dumps({'data': 'Hello, RabbitMQ!'})
    channel.basic_publish(exchange=exchange_name, routing_key=routing_key, body=message)
    
    # Close the connection
    connection.close()