This example demonstrates two servers coupled as a live-backup pair for high availability (HA), and a client connection transparently failing over from live to backup when the live server is crashed.
JBoss Messaging implements seamless, transparent failover of client connections between live and backup servers. This is implemented by the replication of state between live and backup nodes. When replication is configured and a live node crashes, the client connections can carry on as if nothing happened and carry on sending and consuming messages.
With JBoss Messaging there is no need to code any special client side failover logic in order to benefit from failover and HA. There is no need to refactor your messaging applications to work in an HA environment.
JBoss Messaging also supports manual failover which is covered in a separate example.
For more information on JBoss Messaging failover and HA, and clustering in general, please see the clustering section of the user manual.
To run the example, simply type ant
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(false, Session.AUTO_ACKNOWLEDGE);
connection.start();
MessageConsumer consumer = session.createConsumer(queue);
MessageProducer producer = session.createProducer(queue);
final int numMessages = 10;
for (int i = 0; i < numMessages; i++)
{
TextMessage message = session.createTextMessage("This is text message " + i);
producer.send(message);
System.out.println("Sent message: " + message.getText());
}
killServer(1); // This causes the live server to crash
Thread.sleep(2000); // Just wait a little while to make sure the live server has really crashed.
for (int i = 0; i < numMessages; i++)
{
TextMessage message0 = (TextMessage)consumer.receive(5000);
System.out.println("Got message: " + message0.getText());
}
for (int i = numMessages; i < numMessages * 2; i++)
{
TextMessage message = session.createTextMessage("This is text message " + i);
producer.send(message);
System.out.println("Sent message: " + message.getText());
}
for (int i = 0; i < numMessages; i++)
{
TextMessage message0 = (TextMessage)consumer.receive(5000);
System.out.println("Got message: " + message0.getText());
}
finally
block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects
finally
{
if (connection != null)
{
connection.close();
}
if (initialContext != null)
{
initialContext.close();
}
}