You can download this code by clicking the button below.
This code is now available for download.
This code defines three functions for randomly creating a RabbitMQ connection, publishing a random JSON message, and consuming messages. These functions use the PyAMQP library.
Technology Stack : PyAMQP
Code Type : Python Function
Code Difficulty : Intermediate
import random
import pika
import json
def random_amqp_connection():
# This function creates a random connection to a RabbitMQ server
# and returns the connection object and channel object
credentials = pika.PlainCredentials('user', 'password')
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost', 5672, '/', credentials))
channel = connection.channel()
return connection, channel
def random_amqp_publish(channel, queue_name):
# This function publishes a random JSON message to a specified queue
message = json.dumps({'data': random.randint(1, 100)})
channel.basic_publish(exchange='', routing_key=queue_name, body=message)
def random_amqp_consume(channel, queue_name):
# This function sets up a consumer for a specified queue and
# prints out the received messages
def callback(ch, method, properties, body):
print(f"Received {body}")
channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
# Example usage
connection, channel = random_amqp_connection()
random_amqp_publish(channel, 'random_queue')
random_amqp_consume(channel, 'random_queue')
channel.close()
connection.close()