You can download this code by clicking the button below.
This code is now available for download.
This function establishes a connection to a RabbitMQ server, declares an exchange, and publishes a message to the exchange with a specified routing key.
Technology Stack : PyAMQP
Code Type : Function
Code Difficulty : Intermediate
import random
import pika
def random_exchange_publish(exchange, routing_key, message):
# Establish a connection to the RabbitMQ server
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# Declare an exchange of type 'direct' to which messages will be sent
channel.exchange_declare(exchange=exchange, exchange_type='direct')
# Publish a message to the exchange with a specific routing key
channel.basic_publish(exchange=exchange, routing_key=routing_key, body=message)
# Close the connection
connection.close()