ActiveMQ Artemis JMS Shared Consumer Example

# JMS Shared Consumer 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 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

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`

               InitialContext initialContext = getContext();

2. We look-up the JMS topic object from JNDI

               Topic topic = (Topic) initialContext.lookup("/topic/exampleTopic");

3. We look-up the JMS connection factory object from JNDI

               ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("/ConnectionFactory");

4. We create a JMS context

               jmsContext = cf.createContext();

5. We create a JMS Producer.

               JMSProducer producer = jmsContext.createProducer();

6. We create a shared consumer using the subscription name sc1

              JMSConsumer jmsConsumer = jmsContext.createSharedConsumer(topic, "sc1");

7. We then create a second JMS context for a second shared consumer

               jmsContext2 = cf.createContext();

8. we then create the second shared consumer using the same subscription name

               JMSConsumer jmsConsumer2 = jmsContext2.createSharedConsumer(topic, "sc1");

9. we then send 2 messages

               producer.send(topic, "this is a String!");

               producer.send(topic, "this is a second String!") ;

10. we then receive the 2 messages using both shared consumers

               String body = jmsConsumer.receiveBody(String.class, 5000);

               body = jmsConsumer2.receiveBody(String.class, 5000);

11. 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

               finally
               {
                  if (initialContext != null)
                  {
                     initialContext.close();
                  }
                  if (jmsContext != null)
                  {
                     jmsContext.close();
                  }
                   if (jmsContext2 != null)
                   {
                   jmsContext2.close();
                   }
               }