4.3.2. Consuming from a Fanout Exchange

4.3.2. Consuming from a Fanout Exchange

fanout_consumer.py creates a private queue, binds it to the fanout exchange, and reads messages delivered to that queue. If multiple instances of fanout_consumer.py are run, each one has its own private queue. Since each session has a unique session name, using the session name as the name of the server-side queue guarantees that it is unique:

server_queue_name = session.name
session.queue_declare(queue=server_queue_name)
session.exchange_bind(queue=server_queue_name, exchange="amq.fanout")

It then creates a local queue and subscribes it to the server-side queue. Unlike the server-side queue, there is no need to use a globally unique name, since the name of the local queue is meaningful only within the local session. We call the start() method to begin delivery to the local queue:

local_queue_name = "local_queue"
local_queue = session.incoming(local_queue_name)

session.message_subscribe(queue=server_queue_name, destination=local_queue_name)
local_queue.start()

Now we read messages from the local queue, finishing when we receive a message that contains the string “That's all, folks!”:

#  Initialize 'final' and 'content', variables used to identify the last message.
final = "That's all, folks!"   # In a message body, signals the last message
content = ""		       # Content of the last message read

# Read the messages - acknowledge each one
message = None
while content != final:
	message = local_queue.get(timeout=10)
	content = message.body          
        session.message_accept(RangedSet(message.id))
	print content