RabbitMQ Connection and Channel Creation

  • Share this:

Code introduction


This function establishes a connection to the RabbitMQ server and creates a channel. It accepts username, password, and virtual host as parameters.


Technology Stack : PyAMQP, RabbitMQ

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import pika

def random_channel_connection(username, password, virtual_host):
    # Establish a connection to the RabbitMQ server
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(
            host='localhost',
            port=5672,
            virtual_host=virtual_host,
            credentials=pika.PlainCredentials(username, password)
        )
    )
    # Create a channel
    channel = connection.channel()
    return channel