6.5.3. Reading Messages from a Queue with a Message Consumer

6.5.3. Reading Messages from a Queue with a Message Consumer

In this section we will see how to read messages from a queue using a Message Consumer. The code used in this section is taken from Consumer.java. As you will see, this program is extremely similar to the consumer used in for the direct example, differing only in the JNDI property file used and the code used to ensure that each consumer has a queue with a unique name.

The first step is to get a connection and create a session. We also create an exception handler for the connection:

// Load JNDI properties
Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream("fanout.properties"));

//Create the initial context
Context ctx = new InitialContext(properties);

// look up destination and connection factory
Destination destination = (Destination)ctx.lookup(queueName);
ConnectionFactory conFac = (ConnectionFactory)ctx.lookup("qpidConnectionfactory");

Connection connection = conFac.createConnection();
connection.setExceptionListener(new ExceptionListener()
{
    public void onException(JMSException jmse)
    {
        System.err.println(CLASS + ": The sample received an exception through the ExceptionListener");
        System.exit(0);
    }
});

System.out.println(CLASS + ": Creating a non-transacted, auto-acknowledged session");
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

Message consumers need to start the connection in order to receive messages. Create a messageConsumer and start the connection:

MessageConsumer messageConsumer = session.createConsumer(destination);
connection.start();

Now we can read our messages and print them out, terminating when the final message is received:

Message message;
boolean end = false;
while (!end)
{
    message = messageConsumer.receive();
    String text;
    if (message instanceof TextMessage)
    {
        text = ((TextMessage) message).getText();
    }
    else
    {
        byte[] body = new byte[(int) ((BytesMessage) message).getBodyLength()];
        ((BytesMessage) message).readBytes(body);
        text = new String(body);
    }
    if (text.equals("That's all, folks!"))
    {
        System.out.println(CLASS + ": Received final message " + text);
        end = true;
    }
    else
    {
        System.out.println(CLASS + ": Received  message:  " + text);
    }
}

Once we have received all messages, we close the connection and the JNDI context before terminating:

connection.close();
ctx.close();