Java Reference
In-Depth Information
JMSContext
replaces the
Connection
and
Session
objects,
JMSProducer
re-
places the
MessageProducer
object, and
JMSConsumer
replaces the
Mes-
sageConsumer
object in the old version. As you can see in the following code, the
difference between the two approaches is very clear. In the sending method based
on JMS API 1.1 (
sendMessageJMSWithOldAPI
), we note: an excessive object
creation, a mandatory throw of an exception, and a need to explicitly close connec-
tions.
Whereas, in the sending method based on JMS API 2.0 (
sendMes-
sageJMSWithNewdAPI
), we have: the try-with-resources statement that saves the
developer from having to explicitly close the connection and a send code reduced to
the essentials that would fit on one line if we had injected
JMSContext
object.
//Sending message with JMS 1.1
public void
sendMessageJMSWithOldAPI(ConnectionFactory
connectionFactory, Queue destination) throws
JMSException {
Connection connection =
connectionFactory.createConnection();
try {
Session session =
connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer =
session.createProducer(destination);
TextMessage textMessage =
session.createTextMessage("Message send with
the old API");
messageProducer.send(textMessage);
} finally {
connection.close();
}
}
//Sending message with JMS 2.0
public void