Java Reference
In-Depth Information
JMS Messages
This section will give you a basic understanding of the standard (older) API for sending and receiving messages. In
a later section entitled API Enhancements, you will see the newer simplified API. Let's begin by taking a look at a
sample of code using the standard API for sending a message. This example demonstrates how to send a text message
to a queue destination.
...
public void sendMessage() {
if (connection != null) {
System.out.println("Creating Session");
try(Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);) {
myQueue = (Queue) getContext().lookup("jms/javaEERecipesQueue");
MessageProducer producer = session.createProducer(myQueue);
TextMessage message = session.createTextMessage();
message.setText("Java EE 7 Is the Best!");
producer.send(message);
producer.close();
setConnectionString("Message Successfully Sent to Queue");
} catch (NamingException | JMSException ex) {
System.out.println(ex);
setConnectionString("Session not created and message not sent");
}
} else {
setConnectionString("No connection available");
}
}
...
Now let's discuss the example. To send a JMS message using the standard API, you need to create a resource
destination for your message, and obtain a connection as well as a JMS session, as mentioned previously. Once
you have obtained a JMS session, the next step is to create a MessageProducer using the Session createProducer
method, passing the destination as an argument. After this legwork has been completed, the message can be
constructed. You can create a message by calling the javax.jms.Session method that corresponds to the type of
message that you wish to create. To see all of the available methods, please refer to the online documentation at:
http://docs.oracle.com/javaee/6/api/javax/jms/Session.html . In the example shown above, a text message
is created by calling the session.createTextMessage() method. The text is then set by calling the TextMessage
object's setText method.
Once a message has been created, a MessageProducer must be created in order to facilitate the sending of the
message. Again, javax.jms.Session comes to the rescue here, as we can call its createProducer method, passing the
destination resource for which we'd like to create the MessageProducer . Once created, the producer's sendMessage
method can be invoked, passing the message that you wish to send.
As mentioned previously, the javax.jms.Session can be used to generate different message types. Table 10-2
lists the different message types that can be created, along with a description.
 
Search WWH ::




Custom Search