使用Java开源组件Atomikos开发分布式事务应用

2024-04-24 14:08

本文主要是介绍使用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集成。

这篇关于使用Java开源组件Atomikos开发分布式事务应用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/931974

相关文章

Java利用docx4j+Freemarker生成word文档

《Java利用docx4j+Freemarker生成word文档》这篇文章主要为大家详细介绍了Java如何利用docx4j+Freemarker生成word文档,文中的示例代码讲解详细,感兴趣的小伙伴... 目录技术方案maven依赖创建模板文件实现代码技术方案Java 1.8 + docx4j + Fr

SpringBoot首笔交易慢问题排查与优化方案

《SpringBoot首笔交易慢问题排查与优化方案》在我们的微服务项目中,遇到这样的问题:应用启动后,第一笔交易响应耗时高达4、5秒,而后续请求均能在毫秒级完成,这不仅触发监控告警,也极大影响了用户体... 目录问题背景排查步骤1. 日志分析2. 性能工具定位优化方案:提前预热各种资源1. Flowable

Linux中的计划任务(crontab)使用方式

《Linux中的计划任务(crontab)使用方式》:本文主要介绍Linux中的计划任务(crontab)使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、前言1、linux的起源与发展2、什么是计划任务(crontab)二、crontab基础1、cro

kotlin中const 和val的区别及使用场景分析

《kotlin中const和val的区别及使用场景分析》在Kotlin中,const和val都是用来声明常量的,但它们的使用场景和功能有所不同,下面给大家介绍kotlin中const和val的区别,... 目录kotlin中const 和val的区别1. val:2. const:二 代码示例1 Java

C++变换迭代器使用方法小结

《C++变换迭代器使用方法小结》本文主要介绍了C++变换迭代器使用方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、源码2、代码解析代码解析:transform_iterator1. transform_iterat

基于SpringBoot+Mybatis实现Mysql分表

《基于SpringBoot+Mybatis实现Mysql分表》这篇文章主要为大家详细介绍了基于SpringBoot+Mybatis实现Mysql分表的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录基本思路定义注解创建ThreadLocal创建拦截器业务处理基本思路1.根据创建时间字段按年进

C++中std::distance使用方法示例

《C++中std::distance使用方法示例》std::distance是C++标准库中的一个函数,用于计算两个迭代器之间的距离,本文主要介绍了C++中std::distance使用方法示例,具... 目录语法使用方式解释示例输出:其他说明:总结std::distance&n编程bsp;是 C++ 标准

vue使用docxtemplater导出word

《vue使用docxtemplater导出word》docxtemplater是一种邮件合并工具,以编程方式使用并处理条件、循环,并且可以扩展以插入任何内容,下面我们来看看如何使用docxtempl... 目录docxtemplatervue使用docxtemplater导出word安装常用语法 封装导出方

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、