4.2.4. Reading Messages from the Queue
direct_consumer.py creates a local queue, subscribes it to the message queue on the server, reads messages, and prints them out. We start by creating a local client queue using session.incoming():
local_queue_name = "local_queue" local_queue = session.incoming(local_queue_name)
Next, we subscribe this queue to the server-side queue named message_queue:
session.message_subscribe(queue="message_queue", destination=local_queue_name)
Before messages are actually delivered, we have to inform the broker how many messages and how many bytes we are prepared to receive. This is done using session.message_flow(). Since this is a simple example with very little traffic, and we know we can handle the incoming traffic, we will use a significantly large hexadecimal number to tell the broker to send whatever it has:
session.message_flow(local_queue_name, session.credit_unit.message, 0xFFFFFFFF) session.message_flow(local_queue_name, session.credit_unit.byte, 0xFFFFFFFF)
Finally, we read the messages from the local queue, acknowledging each message so it can be removed from the server-side queue:
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 = local_queue.get(timeout=10)
content = message.body
session.message_accept(RangedSet(message.id)) # acknowledge message receipt
print content