Publishing Messages 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 (RabbitMQ)

Code Type : Function

Code Difficulty : Intermediate


                
                    
def publish_message(exchange_name, routing_key, message):
    import pika
    
    # Establishing connection to RabbitMQ server
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    
    # Declaring an exchange
    channel.exchange_declare(exchange=exchange_name, exchange_type='direct')
    
    # Publishing a message to the exchange
    channel.basic_publish(exchange=exchange_name, routing_key=routing_key, body=message)
    
    # Closing the connection
    connection.close()                
              
Tags: