Use Java open-source component atomikos to develop distributed transaction applications

Source: Internet
Author: User
Atomikos is a company name. atomikostransactionsessentials is its Open-Source Distributed Transaction software package, and extremetransactions is a commercial distributed transaction software package. Transactionsessentials is based on Apache-License and is an open-source implementation of JTA/Xa. It supports Java application and J2EE applications. The following uses a AtomikosTransactionsEssentials-3.4.2 (which can be downloaded in a http://www.atomikos.com) as an example to illustrate its usage. Jar package: JTA. jar, transactions-essentials-all.jar. By default, atomikos uses the configuration file transactions. properties under classpath. If the file cannot be found, the default configuration parameters are used. The following is an example of transactions. properties, which can be modified as needed: # sample properties file for the transaction service
# This file has strates 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
# 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
# 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
# Shocould two-phase commit be done in (Multi-) threaded mode or not?
#
# Com. atomikos. icatch. threaded_2pc = true
# Shocould exit of the VM Force shutdown of the transaction core?
#
# Com. atomikos. icatch. force_shutdown_on_vm_exit = false
# Shocould the logs be protected by A. LCK file on startup?
#
# Com. atomikos. icatch. lock_logs = true atomikos transactionsessentials supports three usage modes, which can be selected based on your own situation. The following describes how to use each method and a sample code. 1. Use JDBC/JMS and usertransaction. This is the most direct and simple method of use. Use the built-in JDBC and JMS adapters of atomikos. Example: 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. atomikosperformancebean;

/**
*
*/
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.exe cuteupdate ("insert into T values (1, '23 ')");

Stmt1 = conn1.createstatement ();
Stmt1.executeupdate ("insert into T values (1, '20140901 ')");

}
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 shocould 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 ();
}
}
}
} 2. Use JTA transactionmanager. In this way, you do not need the built-in JDBC and JMS adapters of atomikos, but you need to add or delete XA resource instances at the JTA/XA level. Example: 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.exe cuteupdate ("insert into T values (1, '20140901 ')");
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 shocould 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 ();
}
}
} 3. Use atomikos usertransactionservice. This is an advanced usage method. It can control the startup and shutdown of the Transaction Service and the assembly of resources. Example: 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 cocould
// 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.exe cuteupdate ("insert into T values (1, '20140901 ')");
Stmt. Close ();

Statement stmt1 = conn1.createstatement ();
Stmt1.executeupdate ("insert into T values (1, 'abc ')");
Stmt1.close ();

}
Catch (exception e ){
// An exception means we shocould 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 ();
}
}
} During use, you can also configure resources to the application server and use JNDI to obtain resources. It can also be integrated with spring.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.