4.2.5. Reading Messages from a Queue using a Listener
listener.py receives messages using a message listener. The program provides a method that is called whenever a message is received. Here is the listener class:
class Receiver:
def __init__ (self):
self.finalReceived = False
def isFinal (self):
return self.finalReceived
def Handler (self, message):
content = message.body
session.message_accept(RangedSet(message.id))
print content
if content == "That's all, folks!":
self.finalReceived = True
To use this class in our program, we will register the Handler method with a local queue so that it is called whenever a new message is transferred to this queue. First, we must subscribe the local queue to the server-side queue, as we did in the previous section:
local_queue_name = "local_queue" local_queue = session.incoming(local_queue_name) session.message_subscribe(queue="message_queue", destination=local_queue_name) local_queue.start()
Once this is done, we create a receiver and register the Handler method as a message listener for the local queue:
receiver = Receiver() local_queue.listen (receiver.Handler)
The Handler method acknowledges each message and prints it out when it is received. It also looks for the final message and signals that it is finished by setting self.finalReceived to true. Any Python callable that is called with one Message as a parameter may be used as a message listener callback. Now the code that instructs the handler to finish:
# Add this to the includes in the skeleton from time import sleep # Wait for the receiver to signal that it is done. while not receiver.isFinal() : sleep (1)