You can download this code by clicking the button below.
This code is now available for download.
This function uses the PyAMQP library to create a connection to a local AMQP server and declares a randomly generated queue. It also defines a callback function to receive and print messages, and starts consuming messages from the queue.
Technology Stack : PyAMQP
Code Type : The type of code
Code Difficulty : Advanced
import random
import pika
def random_queue_connection():
# Establish a connection to a random AMQP server
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
# Declare a random queue
queue_name = 'random_queue_' + str(random.randint(1, 1000))
channel.queue_declare(queue=queue_name)
# Define a callback function
def callback(ch, method, properties, body):
print(f"Received {body} from {method.routing_key}")
# Consume messages from the queue
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
# Start consuming messages
print(f"Waiting for messages in {queue_name}. To exit press CTRL+C")
channel.start_consuming()