JMS Completion Listener Example

To run the example, simply type mvn verify from this directory, 
or mvn -PnoServer verify if you want to start and create the server manually.

This example shows you how to send a message asynchronously to ActiveMQ Artemis and use a CompletionListener to be notified of the Broker receiving it

Example step-by-step

  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.
  10.            JMSProducer producer = jmsContext.createProducer();
            
  11. We set a CompletionListener on the Producer
  12.           producer.setAsync(new CompletionListener()
                    {
                       @Override
                       public void onCompletion(Message message)
                       {
                          System.out.println("message acknowledged by ActiveMQ");
                          latch.countDown();
                       }
    
                       @Override
                       public void onException(Message message, Exception e)
                       {
                          e.printStackTrace();
                       }
                    });
           
  13. We send a message
  14.            producer.send(queue, "this is a string");
            
  15. and then wait for the Completion Listener to be called
  16.            return latch.await(5, TimeUnit.SECONDS);
            
  17. 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
  18.            finally
               {
                  if (initialContext != null)
                  {
                     initialContext.close();
                  }
                  if (jmsContext != null)
                  {
                     jmsContext.close();
                  }
               }