This example demonstrates how JBoss Messaging connections can be configured to be resilient to temporary network failures.
In the case of a network failure being detected, either as a result of a failure to read/write to the connection, or the failure of a pong to arrive back from the server in good time after a ping is sent, instead of failing the connection immediately and notifying any user ExceptionListener objects, JBoss Messaging can be configured to automatically retry the connection, and reconnect to the server when it becomes available again across the network.
In the case that the server didn't actually crash, i.e. the network was temporarily unavailable, the client will be able to resume all its sessions and connections where it left off, 100% transparently.
This is very similar to automatic failover, the difference being with automatic failover the reconnection is to a different server, but in this cases the reconnection is to the same server
In the case that the server did crash and was restarted, on reconnection the server session clearly won't still exist, so the session will be unable to continue transparently, and any registered ExceptionListener will be called, to allow any application layer reconnect logic to be called.
This example starts a single server, connects to it and performs some JMS operations. We then simulate failure of the network connection by temporarily stopping the network acceptor on the server. (This is done by sending management messages, but that is not central to the purpose of the example).
We then wait a few seconds, then restart the acceptor. The client reconnects and the session resumes as if nothing happened.
The JMS Connection Factory is configured to reconnect automatically by specifying the various reconnect
related attributes in the jbm-jms.xml
file.
For more details on how to configure this and for clustering in general please consult the JBoss Messaging user manual.
To run the example, simply type ant
from this directory
initialContext = getContext(0);
Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");
ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(topic);
TextMessage message = session.createTextMessage("This is a text message");
messageProducer.send(message);
MessageConsumer messageConsumer = session.createConsumer(queue);
connection.start();
stopAcceptor(initialContext);
Thread.sleep(10000);
startAcceptor(initialContext);
TextMessage messageReceived = (TextMessage)messageConsumer.receive(5000);
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 (connection != null)
{
connection.close();
}
}