4.3.3. Reading Messages from the Queue

4.3.3. Reading Messages from the Queue

We have already seen how to read messages from a queue. The consumer program simply reads from the queue, and does not need to know how the queue is bound to the exchange. Therefore, the code is the same as for the previous example:

# The consumer tag identifies the client-side queue.

consumer_tag = "consumer1"
queue = client.queue(consumer_tag)

session.message_subscribe(queue="message_queue", destination=consumer_tag)
session.message_flow(consumer_tag, 0, 0xFFFFFFFF)
session.message_flow(consumer_tag, 1, 0xFFFFFFFF)

final = "That's all, folks!"   # In a message body, signals the last message
content = ""		       # Content of the last message read

message = None
while content != final:
	message = queue.get(timeout=10)
	content = message.content.body
	print content

message.complete(cumulative=True)

When you run this program, you should be able to see the ten messages you have received in the terminal.

message 0
message 1
message 2
message 3
message 4
message 5
message 6
message 7
message 8
message 9
That's all, folks!

Congratulations! You have successully implemented a fanout application in Python. The configuration program set up a message queue and bound it to a fanout exchange, the publisher wrote messages to the fanout exchange, and the consumer read messages from the queue.