使用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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

JS常用组件收集

收集了一些平时遇到的前端比较优秀的组件,方便以后开发的时候查找!!! 函数工具: Lodash 页面固定: stickUp、jQuery.Pin 轮播: unslider、swiper 开关: switch 复选框: icheck 气泡: grumble 隐藏元素: Headroom

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

这15个Vue指令,让你的项目开发爽到爆

1. V-Hotkey 仓库地址: github.com/Dafrok/v-ho… Demo: 戳这里 https://dafrok.github.io/v-hotkey 安装: npm install --save v-hotkey 这个指令可以给组件绑定一个或多个快捷键。你想要通过按下 Escape 键后隐藏某个组件,按住 Control 和回车键再显示它吗?小菜一碟: <template

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取