RabbitMQ Message Publishing Function

  • Share this:

Code introduction


This function connects to a RabbitMQ server, declares a queue, and sends a message to this queue.


Technology Stack : Python, RMQ (RabbitMQ)

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import pika

def random_rabbitmq_function(queue_name, message):
    # Connect to the RabbitMQ server
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()
    
    # Declare a queue
    channel.queue_declare(queue=queue_name)
    
    # Publish a message to the queue
    channel.basic_publish(exchange='', routing_key=queue_name, body=message)
    
    # Close the connection
    connection.close()