You can download this code by clicking the button below.
This code is now available for download.
This function uses the PyAMQP library to connect to the RabbitMQ server, declares a random type of exchange, and publishes a message to this exchange. It also supports setting the message as mandatory or immediate.
Technology Stack : PyAMQP, RabbitMQ
Code Type : Function
Code Difficulty : Intermediate
def random_exchange_publish(exchange_name, routing_key, body, mandatory=False, immediate=False):
"""
This function publishes a message to a random exchange with a given routing key using PyAMQP.
It also has the option to set the message as mandatory or immediate.
"""
import pika
# Connect to the RabbitMQ server
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# Declare a random exchange
channel.exchange_declare(exchange=exchange_name, exchange_type='direct', durable=True)
# Publish a message to the exchange
channel.basic_publish(exchange=exchange_name, routing_key=routing_key, body=body, mandatory=mandatory, immediate=immediate)
# Close the connection
connection.close()