public void testNetworkFailback() throws Exception {
final long timeout = 5000; // 5 seconds
final String queueName = getClass().getName();
ActiveMQConnectionFactory factoryA = new ActiveMQConnectionFactory(clientUrlA);
ActiveMQConnection connectionA = (ActiveMQConnection) factoryA.createConnection();
connectionA.start();
Session sessionA = connectionA.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queueA = sessionA.createQueue(queueName);
MessageProducer producerA = sessionA.createProducer(queueA);
ActiveMQConnectionFactory factoryB = new ActiveMQConnectionFactory(clientUrlB);
ActiveMQConnection connectionB = (ActiveMQConnection) factoryB.createConnection();
connectionB.start();
Session sessionB = connectionB.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queueB = sessionB.createQueue(queueName);
MessageConsumer consumerB = sessionA.createConsumer(queueB);
// Test initial configuration is working
String msgStr = queueName + "-" + System.currentTimeMillis();
Message msgSent = sessionA.createTextMessage(msgStr);
producerA.send(msgSent);
Message msgReceived = null;
try {
msgReceived = consumerB.receive(timeout);
} catch (JMSException e) {
fail("Message Timeout");
}
assertTrue(msgReceived instanceof TextMessage);
assertEquals(((TextMessage) msgReceived).getText(), msgStr);
// Test Failover
assertTrue(brokerB2.isSlave());
brokerB1.stop();
brokerB2.waitUntilStarted();
assertFalse(brokerB2.isSlave());
msgStr = queueName + "-" + System.currentTimeMillis();
msgSent = sessionA.createTextMessage(msgStr);
producerA.send(msgSent);
try {
msgReceived = consumerB.receive(timeout);
} catch (JMSException e) {
fail("Message Timeout");
}
assertTrue(msgReceived instanceof TextMessage);
assertEquals(((TextMessage)msgReceived).getText(), msgStr);
// Test Failback
new Thread(new Runnable() {
@Override
public void run() {
try {
brokerB1.start();
} catch (Exception e) {
e.printStackTrace();
fail("Failed to start broker");
}
}
}, "BrokerB1 Restarting").start();
brokerB1.waitUntilStarted();
assertTrue(brokerB1.isSlave());
new Thread(new Runnable() {
@Override
public void run() {
try {
brokerB2.stop();
} catch (Exception e) {
e.printStackTrace();
fail("Failed to stop broker");
}
}
}, "BrokerB2 Stopping").start();
brokerB2.waitUntilStopped();
brokerB1.waitUntilStarted();
msgStr = queueName + "-" + System.currentTimeMillis();
msgSent = sessionA.createTextMessage(msgStr);
producerA.send(msgSent);
try {
msgReceived = consumerB.receive(timeout);
} catch (JMSException e) {
fail("Message Timeout");
}
assertTrue(msgReceived instanceof TextMessage);
assertEquals(((TextMessage)msgReceived).getText(), msgStr);
connectionA.close();
connectionB.close();
}