Java Reference
In-Depth Information
A message consumer allows a JMS client to register interest in a destination with a JMS
provider. The JMS provider manages the delivery of messages from a destination to the
registered consumers of the destination.
For example, you could use a
Session
to create a
MessageConsumer
for a
Destination
object, a
Queue
object, or a
Topic
object:
MessageConsumer consumer = session.createConsumer(dest);
MessageConsumer consumer = session.createConsumer(queue);
MessageConsumer consumer = session.createConsumer(topic);
You use the
Session.createDurableSubscriber
method to create a durable
topic subscriber. This method is valid only if you are using a topic. For details, see “
Creat-
ing Durable Subscriptions
”
on page
364
.
After you have created a message consumer it becomes active, and you can use it to re-
ceive messages. You can use the
close
method for a
MessageConsumer
to make
the message consumer inactive. Message delivery does not begin until you start the con-
nection you created by calling its
start
method. (Remember always to call the
start
method; forgetting to start the connection is one of the most common JMS programming
errors.)
You use the
receive
method to consume a message synchronously. You can use this
method at any time after you call the
start
method:
connection.start();
Message m = consumer.receive();
connection.start();
Message m = consumer.receive(1000); // time out after a second
To consume a message asynchronously, you use a message listener, as described in the
next section.
JMS Message Listeners
A message listener is an object that acts as an asynchronous event handler for messages.
This object implements the
MessageListener
interface, which contains one method,
onMessage
. In the
onMessage
method, you define the actions to be taken when a mes-
sage arrives.
You register the message listener with a specific MessageConsumer by using the
setMessageListener
method. For example, if you define a class named
Listener