You can download this code by clicking the button below.
This code is now available for download.
This function establishes a random connection to an AMQP server, creates a random-named queue, defines a callback function for processing messages, and starts consuming messages from the queue.
Technology Stack : PyAMQP
Code Type : Function
Code Difficulty : Intermediate
import random
import pika
def random_channel_connection():
# Establish a random connection to an AMQP server and create a channel
credentials = pika.PlainCredentials('user', 'password')
parameters = pika.ConnectionParameters('localhost', 5672, '/', credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
# Declare a queue with a random name
queue_name = 'random_queue_' + str(random.randint(1000, 9999))
channel.queue_declare(queue=queue_name)
# Define a callback function for processing messages
def callback(ch, method, properties, body):
print(f"Received {body}")
# Set up the callback and start consuming messages from the queue
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
# Print a message indicating the connection and consumption setup
print(f"Connected to RabbitMQ and consuming messages from {queue_name}")
# Return the channel object
return channel