Raj
Raj

Reputation: 389

XA transaction across two separate resource managers/XAResource's

I'm trying to a simple POC involving a ActiveMQ Queue and mySqL Database - An application(Java POJO) reads a message from the queue and inserts it into a table . I want to do this operation in single 2phase commit transaction. I want to have a XA transaction across 2 XA resources. This is what I could come up with but not sure how XAResource works

/**assume the dest queue already has the messages I'm going to consumer here**/
xaDS = getDataSource();
xaCon = xaDS.getXAConnection("jdbc_user", "jdbc_password");
xaRes1 = xaCon.getXAResource();
con = xaCon.getConnection();
stmt = con.createStatement();


ActiveMQXAConnectionFactory cf1 = new ActiveMQXAConnectionFactory("vm://localhost?broker.persistent=false");
XAConnection connection1 = (XAConnection)cf1.createConnection();
        connection1.start();
        XASession session = connection1.createXASession();
        XAResource xaRes2 = session.getXAResource();


xid = new MyXid(100, new byte[]{0x01}, new byte[]{0x02});

xaRes1.start(xid, XAResource.TMNOFLAGS);
xaRes2.start(xid, XAResource.TMNOFLAGS);
        MessageConsumer consumer = session.createConsumer(dest);
        TextMessage receivedMessage = (TextMessage) consumer.receive(10);
        stmt.executeUpdate("insert receivedMessage into Table");
 xaRes1.end(xid, XAResource.TMSUCCESS);
 xaRes2.end(xid, XAResource.TMSUCCESS);

 ret1 = xaRes1.prepare(xid);
 ret2= xaRes2.prepare(xid);
 if ((ret1 == XAResource.XA_OK) && (ret2 == XAResource.XA_OK)) {
    xaRes1.commit(xid, false);
    xaRes2.commit(xid, false);
    }
}

Upvotes: 0

Views: 253

Answers (1)

chalda
chalda

Reputation: 722

I would recommend this article from MSDN https://msdn.microsoft.com/en-us/library/aa342335.aspx

There is nice summary of how to proceed with XAResource.

Then for sure you should consult XA specification http://pubs.opengroup.org/onlinepubs/009680699/toc.pdf

And code of some transction manager - for example Narayana could be big help too: https://github.com/jbosstm/narayana/blob/master/ArjunaJTA/jta/classes/com/arjuna/ats/internal/jta/resources/arjunacore/XAResourceRecord.java You can see here methods topLevelPrepare and topLevelCommit and check handling of all failure possibilities.

Upvotes: 1

Related Questions