Publish Message to RabbitMQ Exchange

  • Share this:

Code introduction


This function is used to publish messages to a RabbitMQ exchange. It requires the exchange name, routing key, and message content.


Technology Stack : RMQ third-party library (pika)

Code Type : RabbitMQ message publishing function

Code Difficulty : Intermediate


                
                    
import random
import pika

def publish_message(exchange_name, routing_key, message):
    # Establish connection to RabbitMQ server
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    
    # Declare an exchange
    channel.exchange_declare(exchange=exchange_name, exchange_type='direct')
    
    # Publish a message
    channel.basic_publish(exchange=exchange_name, routing_key=routing_key, body=message)
    
    # Close the connection
    connection.close()