Using the JMS 2.0 simplified API
to send a message (JavaEESenderNew)
Here is a simple Java EE session bean which demonstrates how to use the JMS 2.0 simplified API to send a message.
@Stateless
@LocalBean
public class JavaEESenderNew {
@Resource(lookup = "java:global/jms/demoConnectionFactory")
ConnectionFactory connectionFactory;
@Resource(lookup = "java:global/jms/demoQueue")
Queue demoQueue;
public void sendMessageNew(String payload) {
try {
JMSContext context = connectionFactory.createContext();
try {
context.createProducer().send(demoQueue, payload);
} finally {
context.close();
}
} catch (JMSRuntimeException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
This example shows:
- Use of a JMS 2.0 JMSContext for sending a message instead of separate Connection and Session objects
- 6 lines of code to send a message (excluding exception handling)
- JMSContext is created explicitly and then closed after use
- No need to specify transacted and acknowledgeMode parameters (unlike with createSession) in Java EE
- No need to create a TextMessage object: message payload is passed directly to the send method
- Still need a try...finally block to ensure close is called,
plus at least one more try block to handle exceptions.
(This will get simpler in JMS 2.0 as the Java 7 try-with-resources syntax can be used to avoid an explicit close(),
but this cannot be demonstrated yet as GlassFish 4.0 still requires Java 6)
This example is for Java EE but the API for Java SE is similar
Now compare this with using the JMS 2.0 simplified API and injection do the same thing
Run this example
JMS 2.0 examples home