6.4.3. Reading Messages from the Queue with a Message Consumer

6.4.3. Reading Messages from the Queue with a Message Consumer

In this section we will see how to read messages from the queue using a Message Consumer. The code used in this section is taken from Consumer.java.

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("direct.properties"));

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

// look up destination and connectoin factory
Destination destination = (Destination)ctx.lookup("directQueue");
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);
    }
});

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();
getInitialContext().close();