Client Side Kickoff Example

This example demonstrates how you can listen on failover event on the client side.

In this example there are two nodes running in a cluster, both server will be running for start, but after a while the first server will crash. This will trigger an fail oever event.

Example step-by-step

To run the example, simply type mvn verify 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 its properties from client-jndi.properties
  2.             InitialContext initialContext = getContext(0);
            
  3. We look up the JMS Queue object from JNDI
  4.             Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue");
            
  5. We look up a JMS Connection Factory object from JNDI on server 0
  6.             ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
            
  7. We create a JMS connection from the same connection factory, wait a little while to make sure broadcasts from all nodes have reached the client
  8.             
                Thread.sleep(5000);
                connectionA = connectionFactory.createConnection();
                ((HornetQConnection)connectionA).setFailoverListener(new FailoverListenerImpl());
    			
            
  9. We create JMS Sessions
  10.             Session sessionA = connectionA.createSession(false, Session.AUTO_ACKNOWLEDGE);
           
  11. We create JMS MessageProducer objects on the sessions
  12.             MessageProducer producerA = sessionA.createProducer(queue);
            
  13. We send some messages on each producer
  14.             
                final int numMessages = 10;
    
                for (int i = 0; i < numMessages; i++)
                {
                   TextMessage messageA = sessionA.createTextMessage("A:This is text message " + i);
                   producerA.send(messageA);
                   System.out.println("Sent message: " + messageA.getText());
                }
    		 
            
  15. We start the connection to consume messages
  16.               connectionA.start();
            
  17. We consume messages from the session A, one at a time. We reached message no 5 the first server will crash
  18.             consume(sessionA, queue, numMessages, "A");
            
  19. 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
  20.            
               if (connectionA != null)
               {
                  connectionA.close();
               }
    
               if (initialContext != null)
               {
                  initialContext.close();
               }