You can download this code by clicking the button below.
This code is now available for download.
This function creates a RabbitMQ consumer to receive and print messages from a specified queue.
Technology Stack : PyAMQP, RabbitMQ
Code Type : Function
Code Difficulty : Intermediate
import random
import pika
def random_queue_consumer(queue_name):
# Establish connection to RabbitMQ server
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# Declare a queue
channel.queue_declare(queue=queue_name)
# Define a callback function for handling messages
def callback(ch, method, properties, body):
print(f"Received message: {body}")
ch.basic_ack(delivery_tag=method.delivery_tag)
# Start consuming messages from the queue
channel.basic_consume(queue=queue_name, on_message_callback=callback)
print(f" [*] Waiting for messages. To exit press CTRL+C")
channel.start_consuming()