JMS Shared Consumer Example

This example shows you how can use shared consumers to share a subscription on a topic. In JMS 1.1 this was not allowed and so caused a scalability issue. In JMS 2 this restriction has been lifted so you can share the load across different threads and connections.

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 topic object from JNDI
  4.            Topic topic = (Topic) initialContext.lookup("/topic/exampleTopic");
            
  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 create a shared consumer using the subscription name sc1
  12.           JMSConsumer jmsConsumer = jmsContext.createSharedConsumer(topic, "sc1");
           
  13. We then create a second JMS context for a second shared consumer
  14.            jmsContext2 = cf.createContext();
            
  15. we then create the second shared consumer using the same subscription name
  16.            JMSConsumer jmsConsumer2 = jmsContext2.createSharedConsumer(topic, "sc1");
            
  17. we then send 2 messages
  18.            
               producer.send(topic, "this is a String!");
    
               producer.send(topic, "this is a second String!") ;
            
  19. we then receive the 2 messages using both shared consumers
  20.            
               String body = jmsConsumer.receiveBody(String.class, 5000);
    
               body = jmsConsumer2.receiveBody(String.class, 5000);
            
  21. 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
  22.            finally
               {
                  if (initialContext != null)
                  {
                     initialContext.close();
                  }
                  if (jmsContext != null)
                  {
                     jmsContext.close();
                  }
                   if (jmsContext2 != null)
                   {
                   jmsContext2.close();
                   }
               }