RabbitMQ Producer Function Overview

  • Share this:

Code introduction


This function uses the RMQ library to create a producer that sends messages to the specified exchange and routing key.


Technology Stack : RMQ (RabbitMQ)

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import random
import pika
from pika.adapters.blocking_connection import BlockingConnection

def rabbitmq_producer(exchange, routing_key, message):
    connection = 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)
    
    print(f"Message '{message}' sent to exchange '{exchange}' with routing key '{routing_key}'")
    connection.close()                
              
Tags: