Each subscriber listens to messages from a queue bound to the exchange. Here’s the subscriber code:
# subscriber.py
import pika
def consume_messages(subscriber_id):
# Connect to RabbitMQ
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host="127.0.0.1",
port="5672",
credentials=pika.credentials.PlainCredentials(
'guest',
'guest',
)
),
)
channel = connection.channel()
# Declare the exchange
channel.exchange_declare(exchange='logs', exchange_type='fanout')
# Create a queue with a random name and bind it to the exchange
result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange='logs', queue=queue_name)
print(f"Subscriber {subscriber_id} waiting for messages. To exit press CTRL+C")
# Callback function to process messages
def callback(ch, method, properties, body):
print(f"Subscriber {subscriber_id} received {body.decode()}")
ch.basic_ack(delivery_tag=method.delivery_tag)
# Start consuming messages
channel.basic_consume(queue=queue_name, on_message_callback=callback)
channel.start_consuming()
if __name__ == "__main__":
subscriber_id = "1" # Change this for different subscribers
consume_messages(subscriber_id)