Low Orbit Flux Logo 2 F

RabbitMQ How to Broadcast to All Consumers

We are going to show you how to broadcast to all consumers using RabbitMQ. This can be achieved using a publish/subscribe model. We also cover this in our RabbitMQ Tutorial.

You are basically going to want to create a fanout exchange. With a fanout exchange the routing key will be ignored. Each consumer will create it’s own temporary queue.

Publisher example:

emit_log.py
import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='logs', exchange_type='fanout') message = ' '.join(sys.argv[1:]) or "info: Hello World!" channel.basic_publish(exchange='logs', routing_key='', body=message) print(" [x] Sent %r" % message) connection.close()

Subscriber example:

receive_logs.py
import pika connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel() channel.exchange_declare(exchange='logs', exchange_type='fanout') result = channel.queue_declare(queue='', exclusive=True) queue_name = result.method.queue channel.queue_bind(exchange='logs', queue=queue_name) print(' [*] Waiting for logs. To exit press CTRL+C') def callback(ch, method, properties, body): print(" [x] %r" % body) channel.basic_consume( queue=queue_name, on_message_callback=callback, auto_ack=True) channel.start_consuming()

You can basically copy and paste the code examples above. Just change them around to fit the project that you are working on.