Distributed | concept | example
In Java, there are three kinds of transactions,
- Simple JDBC-level transactions
- JTA-In an EJB environment, users get transactions and control
- CMP-Controls the transaction entirely by the container, and the user defines the transaction behavior through the bean configuration file
Two or three support distributed transactions, but only distributed transactions in the Java environment.
The following discusses how to implement a distributed transaction in a Java program that accesses multiple data sources in the same transaction. is actually how to use JTA.
This assumes that using an Oracle database, using WebLogic to deploy the application, is done in the following steps:
1. Configure
1.1 Confirm that the database supports distributed transactions-Oracle supports distributed transactions, and JDBC drivers also support distributed transactions
1.2 Configure DataSource in WebLogic
1.2.1. Configure connection pooling, note that the driver should be selected here as thin xa instead of thin
1.2.2. Configure the data source and use the connection pool with the preceding XA
2. Program implementation
2.1. Realize your own XID
Import javax.transaction.xa.*;
public class Myxid implements Xid
{
protected int FormatID;
protected byte gtrid[];
protected byte bqual[];
Public Myxid ()
{
}
Public Myxid (int formatid, byte gtrid[], byte bqual[])
{
This.formatid = FormatID;
This.gtrid = Gtrid;
This.bqual = bqual;
}
public int Getformatid ()
{
return FormatID;
}
Public byte[] Getbranchqualifier ()
{
return bqual;
}
Public byte[] Getglobaltransactionid ()
{
return Gtrid;
}
}2.2. Find the configured data source in the WebLogic through Jndi
Public Xadatasource Getxadatasource ()
Throws Exception
{
InitialContext ctx = new InitialContext (Mgr.getprops ());
xadatasource ds = (xadatasource) ctx.lookup ("Jdbc/xads");
return DS;
}2.3. Use Xadatasource to get xaconnection, use Xaconnection to get xaresource, and make specific data access based on Xaresource. If we lookup multiple Xadatasource here and then get multiple xaresource, we can implement transaction control for multiple data sources.
Xadatasource xads;
Xaconnection Xacon;
XAResource Xares;
Xid Xid;
Connection con;
Statement stmt;
int ret;
Xads = Getxadatasource ();
Xacon = Xads.getxaconnection ();
Xares = Xacon.getxaresource ();
con = xacon.getconnection ();
stmt = Con.createstatement ();
XID = new Myxid (New byte[]{0x01}, New byte[]{0x02});
try {
Xares.start (XID, xaresource.tmnoflags);
Stmt.executeupdate ("INSERT into test_table values (100)");
Xares.end (XID, xaresource.tmsuccess);
ret = Xares.prepare (XID);
if (ret = = XARESOURCE.XA_OK) {
Xares.commit (XID, false);
}
}
catch (Xaexception e) {
E.printstacktrace ();
}
finally {
Stmt.close ();
Con.close ();
Xacon.close ();
}