使用Java開源組件Atomikos開發分佈式事務應用

    Atomikos是一個公司的名字,AtomikosTransactionsEssentials是其開源的分佈式事務軟件包,而ExtremeTransactions是商業的分佈式事務軟件包。TransactionsEssentials是基於apache-license的,是JTA/XA的開源實現,支持Java Application和J2EE應用。
    下面以AtomikosTransactionsEssentials-3.4.2(可以在http://www.atomikos.com下載)爲例,說明其用法。
    需要的jar包:jta.jar、transactions-essentials-all.jar。
    Atomikos默認在classpath下使用名爲transactions.properties的配置文件,如果找不到,則使用默認的配置參數。下面給一個transactions.properties的例子,可以根據自己的需要修改:
#SAMPLE PROPERTIES FILE FOR THE TRANSACTION SERVICE
#THIS FILE ILLUSTRATES THE DIFFERENT SETTINGS FOR THE TRANSACTION MANAGER
#UNCOMMENT THE ASSIGNMENTS TO OVERRIDE DEFAULT VALUES;
#Required: factory class name for the transaction service core.
#
com.atomikos.icatch.service=com.atomikos.icatch.standalone.UserTransactionServiceFactory
#
#Set name of file where messages are output
#
#com.atomikos.icatch.console_file_name = tm.out
#Size limit (in bytes) for the console file;
#negative means unlimited.
#
#com.atomikos.icatch.console_file_limit=-1
#For size-limited console files, this option
#specifies a number of rotating files to
#maintain.
#
#com.atomikos.icatch.console_file_count=1
#Set the number of log writes between checkpoints
#
#com.atomikos.icatch.checkpoint_interval=500
#Set output directory where console file and other files are to be put
#make sure this directory exists!
#
#com.atomikos.icatch.output_dir = ./
#Set directory of log files; make sure this directory exists!
#
#com.atomikos.icatch.log_base_dir = ./
#Set base name of log file
#this name will be used as the first part of
#the system-generated log file name
#
#com.atomikos.icatch.log_base_name = tmlog
#Set the max number of active local transactions
#or -1 for unlimited.
#
#com.atomikos.icatch.max_actives = 50
#Set the max timeout (in milliseconds) for local transactions
#
#com.atomikos.icatch.max_timeout = 300000
#The globally unique name of this transaction manager process
#override this value with a globally unique name
#
#com.atomikos.icatch.tm_unique_name = tm
#Do we want to use parallel subtransactions? JTA's default
#is NO for J2EE compatibility.
#
#com.atomikos.icatch.serial_jta_transactions=true
#If you want to do explicit resource registration then
#you need to set this value to false. See later in
#this manual for what explicit resource registration means.
#
#com.atomikos.icatch.automatic_resource_registration=true
#Set this to WARN, INFO or DEBUG to control the granularity
#of output to the console file.
#
#com.atomikos.icatch.console_log_level=WARN
#Do you want transaction logging to be enabled or not?
#If set to false, then no logging overhead will be done
#at the risk of losing data after restart or crash.
#
#com.atomikos.icatch.enable_logging=true
#Should two-phase commit be done in (multi-)threaded mode or not?
#
#com.atomikos.icatch.threaded_2pc=true
#Should exit of the VM force shutdown of the transaction core?
#
#com.atomikos.icatch.force_shutdown_on_vm_exit=false
#Should the logs be protected by a .lck file on startup?
#
#com.atomikos.icatch.lock_logs=true
    Atomikos TransactionsEssentials支持3種使用方式,可以根據自己的情況選用,下面給出每種方式的使用場合和一個代碼示例。
    一、使用JDBC/JMS和UserTransaction,這是最直接和最簡單的使用方式,使用Atomikos內置的JDBC、JMS適配器。示例如下:
package demo.atomikos;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.transaction.UserTransaction;

import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.jdbc.AtomikosDataSourceBean;

/**
*
*/
public class UserTransactionUtil {

public static UserTransaction getUserTransaction() {
UserTransaction utx = new UserTransactionImp();
return utx;
}

private static AtomikosDataSourceBean dsBean;

private static AtomikosDataSourceBean getDataSource() {
if (dsBean != null) return dsBean;
AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
ds.setUniqueResourceName("db");
ds.setXaDataSourceClassName("oracle.jdbc.xa.client.OracleXADataSource");
Properties p = new Properties();
p.setProperty("user", "db_user_name" );
p.setProperty("password", "db_user_pwd");
p.setProperty("URL", "jdbc:oracle:thin:@192.168.0.10:1521:oradb");
ds.setXaProperties(p);
ds.setPoolSize(5);
dsBean = ds;
return dsBean;
}

public static Connection getDbConnection() throws SQLException{
Connection conn = getDataSource().getConnection();
return conn;
}

private static AtomikosDataSourceBean dsBean1;

private static AtomikosDataSourceBean getDataSource1() {
if (dsBean1 != null) return dsBean1;
AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
ds.setUniqueResourceName("db1");
ds.setXaDataSourceClassName("oracle.jdbc.xa.client.OracleXADataSource");
Properties p = new Properties();
p.setProperty("user", "db_user_name" );
p.setProperty("password", "db_user_pwd");
p.setProperty("URL", "jdbc:oracle:thin:@192.168.0.11:1521:oradb1");
ds.setXaProperties(p);
ds.setPoolSize(5);
dsBean1 = ds;
return dsBean1;
}

public static Connection getDb1Connection() throws SQLException{
Connection conn = getDataSource1().getConnection();
return conn;
}

public static void main(String[] args) {
UserTransaction utx = getUserTransaction();
boolean rollback = false;
try {
//begin a transaction
utx.begin();

//execute db operation
Connection conn = null;
Connection conn1 = null;
Statement stmt = null;
Statement stmt1 = null;
try {
conn = getDbConnection();
conn1 = getDb1Connection();

stmt = conn.createStatement();
stmt.executeUpdate("insert into t values(1,'23')");

stmt1 = conn1.createStatement();
stmt1.executeUpdate("insert into t values(1,'123456789')");

}
catch(Exception e) {
throw e;
}
finally {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
if (stmt1 != null) stmt1.close();
if (conn1 != null) conn1.close();
}
}
catch(Exception e) {
//an exception means we should not commit
rollback = true;
e.printStackTrace();
}
finally {
try {
//commit or rollback the transaction
if ( !rollback ) utx.commit();
else utx.rollback();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
    二、使用JTA TransactionManager。這種方式不需要Atomikos內置的JDBC、JMS適配器,但需要在JTA/XA級別上添加、刪除XA資源實例。示例如下:
package demo.atomikos;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.XAConnection;
import javax.transaction.Transaction;
import javax.transaction.xa.XAResource;

import oracle.jdbc.xa.client.OracleXADataSource;

import com.atomikos.icatch.jta.UserTransactionManager;

public class TransactionManagerUtil {
public static UserTransactionManager getUserTransactionManager() throws Exception {
return new UserTransactionManager();
}

private static OracleXADataSource xads;

private static OracleXADataSource getXADataSource() throws SQLException{
if (xads != null) return xads;
xads = new OracleXADataSource();
xads.setUser ("db_user_name");
xads.setPassword("db_user_pwd");
xads.setURL("jdbc:oracle:thin:@192.168.0.10:1521:oradb");
return xads;
}

public static XAConnection getXAConnection() throws SQLException{
OracleXADataSource ds = getXADataSource();
return ds.getXAConnection();
}

private static OracleXADataSource xads1;

private static OracleXADataSource getXADataSource1() throws SQLException{
if (xads1 != null) return xads1;
xads1 = new OracleXADataSource();
xads1.setUser ("db_user_name");
xads1.setPassword("db_user_pwd");
xads1.setURL("jdbc:oracle:thin:@192.168.0.11:1521:oradb1");
return xads1;
}

public static XAConnection getXAConnection1() throws SQLException{
OracleXADataSource ds = getXADataSource1();
return ds.getXAConnection();
}

public static void main(String[] args) {
try {
UserTransactionManager tm = getUserTransactionManager();

XAConnection xaconn = getXAConnection();
XAConnection xaconn1 = getXAConnection1();

boolean rollback = false;
try {
//begin and retrieve tx
tm.begin();
Transaction tx = tm.getTransaction();

//get the XAResourc from the JDBC connection
XAResource xares = xaconn.getXAResource();
XAResource xares1 = xaconn1.getXAResource();

//enlist the resource with the transaction
//NOTE: this will only work if you set the configuration parameter:
//com.atomikos.icatch.automatic_resource_registration=true
//or, alternatively, if you use the UserTransactionService
//integration mode
tx.enlistResource(xares);
tx.enlistResource(xares1);

//access the database, the work will be
//subject to the outcome of the current transaction
Connection conn = xaconn.getConnection();
Statement stmt = conn.createStatement();
stmt.executeUpdate("insert into t values(1,'1234567')");
stmt.close();
conn.close();
Connection conn1 = xaconn1.getConnection();
Statement stmt1 = conn1.createStatement();
stmt1.executeUpdate("insert into t values(1,'abc1234567890')");
stmt1.close();
conn1.close();

//delist the resource
tx.delistResource(xares, XAResource.TMSUCCESS);
tx.delistResource(xares1, XAResource.TMSUCCESS);
}
catch ( Exception e ) {
//an exception means we should not commit
rollback = true;
throw e;
}
finally {
//ALWAYS terminate the tx
if (rollback) tm.rollback();
else tm.commit();

//only now close the connection
//i.e., not until AFTER commit or rollback!
xaconn.close();
xaconn1.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
    三、使用Atomikos UserTransactionService。這是高級使用方式,可以控制事務服務的啓動和關閉,並且可以控制資源的裝配。示例如下:
package demo.atomikos;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.XAConnection;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import javax.transaction.xa.XAResource;

import oracle.jdbc.xa.client.OracleXADataSource;

import com.atomikos.datasource.xa.jdbc.JdbcTransactionalResource;
import com.atomikos.icatch.config.TSInitInfo;
import com.atomikos.icatch.config.UserTransactionService;
import com.atomikos.icatch.config.UserTransactionServiceImp;

public class UserTransactionServiceUtil {
public static UserTransactionService getUserTransactionService() throws Exception {
return new UserTransactionServiceImp();
}

private static OracleXADataSource xads;

private static OracleXADataSource getXADataSource() throws SQLException{
if (xads != null) return xads;
xads = new OracleXADataSource();
xads.setUser ("db_user_name");
xads.setPassword("db_user_pwd");
xads.setURL("jdbc:oracle:thin:@192.168.0.10:1521:oradb");
return xads;
}

public static XAConnection getXAConnection() throws SQLException{
OracleXADataSource ds = getXADataSource();
return ds.getXAConnection();
}

private static JdbcTransactionalResource jdbcResource;

public static JdbcTransactionalResource getJdbcTransactionalResource() throws SQLException{
if (jdbcResource != null) return jdbcResource;
jdbcResource = new JdbcTransactionalResource (
"db"
,getXADataSource()
,new com.atomikos.datasource.xa.OraXidFactory() //oracle db need this
);
return jdbcResource;
}

private static OracleXADataSource xads1;

private static OracleXADataSource getXADataSource1() throws SQLException{
if (xads1 != null) return xads1;
xads1 = new OracleXADataSource();
xads1.setUser ("db_user_name");
xads1.setPassword("db_user_pwd");
xads1.setURL("jdbc:oracle:thin:@192.168.0.11:1521:oradb1");
return xads1;
}

public static XAConnection getXAConnection1() throws SQLException{
OracleXADataSource ds = getXADataSource1();
return ds.getXAConnection();
}

private static JdbcTransactionalResource jdbcResource1;

public static JdbcTransactionalResource getJdbcTransactionalResource1() throws SQLException{
if (jdbcResource1 != null) return jdbcResource1;
jdbcResource1 = new JdbcTransactionalResource (
"db1"
,getXADataSource1()
,new com.atomikos.datasource.xa.OraXidFactory() //oracle db need this
);
return jdbcResource1;
}

public static void main(String[] args) {
try {

//Register the resource with the transaction service
//this is done through the UserTransaction handle.
//All UserTransaction instances are equivalent and each
//one can be used to register a resource at any time.
UserTransactionService uts = getUserTransactionService();
uts.registerResource(getJdbcTransactionalResource());
uts.registerResource(getJdbcTransactionalResource1());

//Initialize the UserTransactionService.
//This will start the TM and recover
//all registered resources; you could
//call this 'eager recovery' (as opposed to 'lazy recovery'
//for the simple xa demo).
TSInitInfo info = uts.createTSInitInfo();
//optionally set config properties on info
info.setProperty("com.atomikos.icatch.checkpoint_interval", "2000");
uts.init(info);

TransactionManager tm = uts.getTransactionManager();
tm.setTransactionTimeout(60);

XAConnection xaconn = getXAConnection();
XAConnection xaconn1 = getXAConnection1();

boolean rollback = false;

//begin and retrieve tx
tm.begin();
Transaction tx = tm.getTransaction();

//get the XAResourc from the JDBC connection
XAResource xares = xaconn.getXAResource();
XAResource xares1 = xaconn1.getXAResource();

Connection conn = xaconn.getConnection();
Connection conn1 = xaconn1.getConnection();
try {

//enlist the resource with the transaction
//NOTE: this will only work if you set the configuration parameter:
//com.atomikos.icatch.automatic_resource_registration=true
//or, alternatively, if you use the UserTransactionService
//integration mode
tx.enlistResource(xares);
tx.enlistResource(xares1);

//access the database, the work will be
//subject to the outcome of the current transaction
Statement stmt = conn.createStatement();
stmt.executeUpdate("insert into t values(1,'1234567')");
stmt.close();

Statement stmt1 = conn1.createStatement();
stmt1.executeUpdate("insert into t values(1,'abc')");
stmt1.close();

}
catch ( Exception e ) {
//an exception means we should not commit
rollback = true;
throw e;
}
finally {
int flag = XAResource.TMSUCCESS;
if (rollback) flag = XAResource.TMFAIL;

tx.delistResource(xares, flag);
tx.delistResource(xares1, flag);

conn.close();
conn1.close();

if (!rollback) tm.commit();
else tm.rollback();
}

uts.shutdown(false);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
    在使用的時候,也可以把資源等配置到應用服務器中,使用JNDI獲取資源。也可以與spring集成。
發佈了35 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章