You can download this code by clicking the button below.
This code is now available for download.
This function is used to send messages to a specified exchange and routing key in RabbitMQ. It first connects to the RabbitMQ server, then declares the exchange, and finally publishes the message and closes the connection.
Technology Stack : PyAMQP, RabbitMQ
Code Type : RabbitMQ news release
Code Difficulty : Intermediate
import random
import pika
def publish_message(exchange, routing_key, message):
# Connect to the RabbitMQ server
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# Declare the exchange
channel.exchange_declare(exchange=exchange, exchange_type='direct')
# Publish a message
channel.basic_publish(exchange=exchange, routing_key=routing_key, body=message)
# Close the connection
connection.close()