5.3.2. Consuming from a Fanout Exchange

5.3.2. Consuming from a Fanout Exchange

The first program in the fanout example, listener.cpp, creates a private queue, binds it to the amq.fanout exchange, and waits for messages to arrive on the queue, printing them out as they arrive. It uses a Listener that is identical to the one used in the direct example:

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

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

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());
    }
}

The listener creates a private queue to receive its messages and binds it to the fanout exchange:

        std::string myQueue=session.getId().str();
        session.queueDeclare(arg::queue=myQueue, arg::exclusive=true, arg::autoDelete=true);

        session.exchangeBind(arg::exchange="amq.fanout", arg::queue=myQueue);

Now we create a listener and subscribe it to the queue:

        SubscriptionManager subscriptions(session);
        Listener listener(subscriptions);
        subscriptions.subscribe(listener, myQueue);

After we subscribe to the queues, we call session.sync() to ensure that all queues and bindings are in place before we run the subscription manager:

        session.sync();

Then we run the subscription manager. Whenever a message is received, the message listener is invoked to print out the message. The call to subscriptions.run() terminates when the message listener calls subscriptions.cancel() to indicate that it is finished.

        std::cout << "Listening" << std::endl;
        subscriptions.run();