This example demonstrates two servers coupled as a live-backup pair for high availability (HA), and a client connection failing over from live to backup when the live server is crashed.
Failover behavior differs whether the JMS session is transacter or not.
When a transacted JMS session is used, once-and-only once delivery is guaranteed.
HornetQ also provides an example for non-transaction failover.
For more information on HornetQ failover and HA, and clustering in general, please see the clustering section of the user manual.
To run the example, simply type mvn verify
from this directory
In this example, the live server is server 1, and the backup server is server 0
The connection will initially be created to server1, server 1 will crash, and the client will carry on seamlessly on server 0, the backup server.
initialContext = getContext(1);
Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue"); ConnectionFactory connectionFactory = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
connection = connectionFactory.createConnection();
Session session = connection.createSession(true, 0);
connection.start();
MessageProducer producer = session.createProducer(queue);
MessageConsumer consumer = session.createConsumer(queue);
sendMessages(session, producer, numMessages, true);
When server #1 crashes, the client automatically detects the failure and automatically fails over from server #1 to server #0 (in your real program you wouldn't need to sleep).
try { session.commit(); } catch (TransactionRolledBackException e) { System.err.println("transaction has been rolled back: " + e.getMessage()); }
sendMessages(session, producer, numMessages, false);
session.commit();
for (int i = 0; i < numMessages; i++) { TextMessage message0 = (TextMessage)consumer.receive(5000); System.out.println("Got message: " + message0.getText()); } session.commit(); System.out.println("Other message on the server? " + consumer.receive(5000));
finally
block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objectsfinally { if (connection != null) { connection.close(); } if (initialContext != null) { initialContext.close(); } }