RabbitMQ Message Publishing Function

  • Share this:

Code introduction


This function uses the PyAMQP library to publish a message to a RabbitMQ queue. It accepts the exchange name, routing key, and message content as parameters.


Technology Stack : PyAMQP, RabbitMQ

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import random

def random_queue_publish(exchange, routing_key, message):
    import pika
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    channel.exchange_declare(exchange=exchange, exchange_type='direct')
    channel.basic_publish(exchange=exchange, routing_key=routing_key, body=message)
    connection.close()