5.2.4. Reading Messages from the Queue

5.2.4. Reading Messages from the Queue

The third program in the direct example, listener.cpp, is a message listener that receives messages from a queue.

To create a message listener, create a class derived from MessageListener, and override the received method, providing the code that should be executed when a message is received. This listener uses a subscription manager, part of the MRG Messaging library, to subscribe to and receive messages from a queue.

class Listener : public MessageListener{
  private:
    SubscriptionManager& subscriptions;
  public:
    Listener(SubscriptionManager& subscriptions);
    virtual void received(Message& message);
};

Define a constructor that initializes the listener's subscriptions.

Listener::Listener(SubscriptionManager& subs) : subscriptions(subs)
{}

The main body of the program creates a subscription manager for the session; creates a listener for the subscription; subscribes the subscription manager to a message queue; and runs the subscription manager to receive messages from the queue.

SubscriptionManager subscriptions(session);

// Create a listener and subscribe it to the queue named "message_queue"
Listener listener(subscriptions);
subscriptions.subscribe(listener, "message_queue");

// Deliver messages until the subscription is cancelled
// by Listener::received()
subscriptions.run();

The MessageListener's received() function is called whenever a message is received. In this example the message is printed and tested to see if it is the final message. Once the final message is received, the subscription to the queue is cancelled.

void Listener::received(Message& message) {
  std::cout << "Message: " << message.getData() << std::endl;
  if (message.getData() == "That's all, folks!") {
      std::cout << "Shutting down listener for " << message.getDestination()
                << std::endl;
      subscriptions.cancel(message.getDestination());
  }
}