JMS Context Example

This example shows you how to send and receive a message to a JMS Queue using ActiveMQ by using a JMS Context

A JMSContext is part of JMS 2.0 and combines the JMS Connection and Session Objects into a simple Interface

Example step-by-step

To run the example, simply type mvn verify -Pexample from this directory

  1. First we need to get an initial context so we can look-up the JMS connection factory and destination objects from JNDI. This initial context will get it's properties from the client-jndi.properties file in the directory ../common/config
  2.            InitialContext initialContext = getContext();
            
  3. We look-up the JMS queue object from JNDI
  4.            Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");
            
  5. We look-up the JMS connection factory object from JNDI
  6.            ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");
            
  7. We create a JMS context
  8.            jmsContext = cf.createContext();
            
  9. We create a JMS Producer, set the delivery mode and send a message all in one line. Note that we don't pass a message to the send method but just a String.
  10.            jmsContext.createProducer().setDeliveryMode(DeliveryMode.PERSISTENT).send(queue, "this is a string")
            
  11. We create a JMS message consumer and receive the payload of the message directly
  12.           String payLoad = jmsContext.createConsumer(queue).receiveBody(String.class);
           
  13. We create a JMS text message that we are going to send.
  14.            TextMessage message = session.createTextMessage("This is a text message");
            
  15. And finally, always remember to close your JMS connections and resources after use, in a finally block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects
  16.            finally
               {
                  if (initialContext != null)
                  {
                     initialContext.close();
                  }
                  if (jmsContext != null)
                  {
                     jmsContext.close();
                  }
               }