This example shows you how message sending behaves in an XA transaction in HornetQ. When a message is sent within the scope of an XA transaction, it will only reach the queue once the transaction is committed. If the transaction is rolled back the sent messages will be discarded by the server.
HornetQ is JTA aware, meaning you can use HornetQ in a XA transactional environment and participate in XA transactions. It provides the javax.transaction.xa.XAResource interface for that purpose. Users can get a XAConnectionFactory to create XAConnections and XASessions.
In this example we simulate a transaction manager to control the transactions. First we create an XASession and enlist it in a transaction through its XAResource. We then send two words, 'hello' and 'world', with the session, let the transaction roll back. The messages are discarded and never be received. Next we start a new transaction with the same XAResource, but this time we commit the transaction. Both messages are received.
To run the example, simply type mvn verify
from this directory
client-jndi.properties
file in the directory ../common/config
InitialContext initialContext = getContext(0);
Queue queue = (Queue) initialContext.lookup("/queue/exampleQueue");
XAConnectionFactory cf = (XAConnectionFactory) initialContext.lookup("/XAConnectionFactory");
connection = cf.createXAConnection();
connection.start();
XASession xaSession = connection.createXASession();
Session normalSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer normalConsumer = normalSession.createConsumer(queue);
normalConsumer.setMessageListener(new SimpleMessageListener());
Session session = xaSession.getSession();
MessageProducer producer = session.createProducer(queue);
TextMessage helloMessage = session.createTextMessage("hello");
TextMessage worldMessage = session.createTextMessage("world");
Xid xid1 = new XidImpl("xa-example1".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
XAResource xaRes = xaSession.getXAResource();
xaRes.start(xid1, XAResource.TMNOFLAGS);
producer.send(helloMessage);
producer.send(worldMessage);
checkNoMessageReceived();
xaRes.end(xid1, XAResource.TMSUCCESS);
xaRes.prepare(xid1);
xaRes.rollback(xid1);
checkNoMessageReceived();
Xid xid2 = new XidImpl("xa-example2".getBytes(), 1, UUIDGenerator.getInstance().generateStringUUID().getBytes());
xaRes.start(xid2, XAResource.TMNOFLAGS);
producer.send(helloMessage);
producer.send(worldMessage);
xaRes.end(xid2, XAResource.TMSUCCESS);
xaRes.prepare(xid2);
checkNoMessageReceived();
xaRes.commit(xid2, false);
checkAllMessageReceived();
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();
}
}