Java Reference
In-Depth Information
Consuming Messages
Let's take a look at how to consume messages using the simplified API. Utilize a
JMSContext
object to create the
JMSConsumer
in an efficient and simplified manner. The following example method resides within a managed bean
controller. The message consumer in this example will be created and set up to receive the message that was sent by
the producer in the previous example.
public String receiveMessage() {
JMSContext context = connectionFactory.createContext();
JMSConsumer consumer = context.createConsumer(inboundQueue);
return consumer.receiveBody(String.class);
}
A client that receives a message is also known as the message consumer. Message consumers can be created
using the standard or the simplified JMS API. As you can see from the example above, there are very few lines of code
needed to create a message consumer using the simplified API. The
JMSContext
object aids in producing less code
by calling its
createConsumer
method and passing the resource from which the application will need to consume
messages. This method call will return a
JMSConsumer
, which has a similar API to
MessageConsumer
, with the ability
to receive a message both synchronously and asynchronously. In the example, a String message is consumed
synchronously.
It is possible to create an asynchronous consumer by registering a
MessageListener
with the
MessageConsumer
.
After a listener has been registered for the consumer, the listener's
onMessage()
method will be called each time a
message has been delivered. The following code demonstrates how to create a simple message listener that will be
used to display the received message in the server log.
public class AcmeMessageListener implements MessageListener {
@Override
public void onMessage(Message message) {
try {
System.out.println("Do something with this message: " + message.getBody(String.class));
} catch (JMSException ex) {
Logger.getLogger(AcmeMessageListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
To register the message listener with a consumer, call the consumer
setMessageListener
method, passing the
listener.
JMSContext context = connectionFactory.createContext();
JMSConsumer consumer = context.createConsumer(inboundQueue);
javax.jms.MessageListener acmeMessageListener = new AcmeMessageListener();
consumer.setMessageListener(acmeMessageListener);
messageReceived = consumer.receiveBody(String.class);