使用spring+mybatis+atomikos+tomcat构建分布式事务

时间:2023-03-09 05:43:36
使用spring+mybatis+atomikos+tomcat构建分布式事务

本文通过一个demo,介绍如何使用spring+mybatis+atomikos+tomcat构建在一个事务中涉及两个数据源的web应用。

demo功能:实现一个能成功提交和回滚的涉及两个数据库数据源的XA事务。

demo将实现:

1.一次性在两个数据库的两张表中各插入一条数据并提交。

2.一次性在两个数据库的两张表中各插入一条数据并回滚。

测试方式:restful web api

使用工具:

spring 4.1.1.RELEASE

mybatis 3.2.7

atomikos 3.7.0

tomcat 7

在mysql中建立两个schema,分别为dev和qa。并在里面分别建立一张名字表。

schema:dev

table:namaDev

id | nameDev

scheme:qa

table:nameQa

id  |  nameQa

对应的sql为

 CREATE SCHEMA `qa` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
CREATE SCHEMA `dev` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ; CREATE TABLE `dev`.`nameDev` (
`id` BIGINT NOT NULL AUTO_INCREMENT ,
`nameDev` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC) ); CREATE TABLE `qa`.`nameQa` (
`id` BIGINT NOT NULL AUTO_INCREMENT ,
`nameQa` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC) );

代码分析:

本项目使用spring框架,因此首先配置相关bean

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="com.xy">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:property-placeholder location="classpath:context/database.properties"/>
<tx:annotation-driven/> <bean id="abstractXADataSource" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init"
destroy-method="close" abstract="true">
<property name="xaDataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"/>
<property name="poolSize" value="10" />
<property name="minPoolSize" value="10"/>
<property name="maxPoolSize" value="30"/>
<property name="borrowConnectionTimeout" value="60"/>
<property name="reapTimeout" value="20"/>
<!-- 最大空闲时间 -->
<property name="maxIdleTime" value="60"/>
<property name="maintenanceInterval" value="60"/>
<property name="loginTimeout" value="60"/>
<property name="testQuery">
<value>select 1</value>
</property>
</bean> <bean id="qadataSource" parent="abstractXADataSource">
<!-- value只要两个数据源不同就行,随便取名 -->
<property name="uniqueResourceName" value="mysql/sitestone1" />
<property name="xaDataSourceClassName"
value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" />
<property name="xaProperties">
<props>
<prop key="URL">${qa.db.url}</prop>
<prop key="user">${qa.db.user}</prop>
<prop key="password">${qa.db.password}</prop>
<prop key="pinGlobalTxToPhysicalConnection">true</prop>
</props>
</property>
</bean> <bean id="devdataSource" parent="abstractXADataSource">
<!-- value只要两个数据源不同就行,随便取名 -->
<property name="uniqueResourceName" value="mysql/sitestone" />
<property name="xaDataSourceClassName"
value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" />
<property name="xaProperties">
<props>
<prop key="URL">${dev.db.url}</prop>
<prop key="user">${dev.db.user}</prop>
<prop key="password">${dev.db.password}</prop>
<prop key="pinGlobalTxToPhysicalConnection">true</prop>
</props>
</property>
</bean> <bean id="qasqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="qadataSource" />
<property name="mapperLocations" value="classpath*:com/xy/dao/*.xml" />
</bean> <bean id="devsqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="devdataSource" />
<property name="mapperLocations" value="classpath*:com/xy/daodev/*.xml" />
</bean> <bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager"
init-method="init" destroy-method="close">
<property name="forceShutdown">
<value>true</value>
</property>
</bean>
<bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp">
<property name="transactionTimeout" value="300" />
</bean> <bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager">
<ref bean="atomikosTransactionManager"/>
</property>
<property name="userTransaction">
<ref bean="atomikosUserTransaction"/>
</property>
<!-- 必须设置,否则程序出现异常 JtaTransactionManager does not support custom isolation levels by default -->
<property name="allowCustomIsolationLevels" value="true"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xy.dao"/>
<property name="sqlSessionFactoryBeanName" value="qasqlSessionFactory" />
</bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xy.daodev"/>
<property name="sqlSessionFactoryBeanName" value="devsqlSessionFactory" />
</bean>
</beans>

其中qadataSource和devdataSource是对应两个数据库的数据源,qasqlSessionFactory和devsqlSessionFactory是mybatis的sessionfactory,两个MapperScannerConfigurer自动将不同数据源的sql语句文件与interface自动装配起来,atomikosTransactionManager会自动管理两个atomikos的数据源的事务,即resource manager,atomikosUserTransaction为最上层的事务管理器为transaction manager。(关于RM和TM,请参见上篇博文)。

Model类如下:package com.xy.model

 package com.xy.model;

 /**
* Created by helloworld on 2015/1/30.
*/
public class NameQa {
private long id;
private String nameQa; public long getId() {
return id;
} public void setId(long id) {
this.id = id;
} public String getNameQa() {
return nameQa;
} public void setNameQa(String nameQa) {
this.nameQa = nameQa;
}
}

nameQa class

 package com.xy.model;

 /**
* Created by helloworld on 2015/1/30.
*/
public class NameDev {
private long id;
private String nameDev; public long getId() {
return id;
} public void setId(long id) {
this.id = id;
} public String getNameDev() {
return nameDev;
} public void setNameDev(String nameDev) {
this.nameDev = nameDev;
}
}

nameDev class

qa数据源的mybatis mapper接口 package com.xy.dao

 package com.xy.dao;

 import com.xy.model.NameQa;

 /**
* Created by helloworld on 2015/1/30.
*/
public interface NameQaMapper {
int insert(NameQa nameQa);
}

NameQaMapper

dev数据源的mybatis mapper接口 package com.xy.devdao

 package com.xy.daodev;

 import com.xy.model.NameDev;

 /**
* Created by helloworld on 2015/1/30.
*/
public interface NameDevMapper {
int insert(NameDev nameDev);
}

NameDevMapper

处理事务的service

 package com.xy.service;

 import com.xy.dao.NameQaMapper;
import com.xy.daodev.NameDevMapper;
import com.xy.model.NameDev;
import com.xy.model.NameQa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; /**
* Created by helloworld on 2015/1/30.
*/
@Service
public class NameService {
@Autowired
NameQaMapper nameQaMapper;
@Autowired
NameDevMapper nameDevMapper; @Transactional(rollbackFor = Exception.class)
public void addQaAndDev(boolean hasException) throws Exception {
NameQa nameQa = new NameQa();
nameQa.setNameQa("qa");
nameQaMapper.insert(nameQa); NameDev nameDev = new NameDev();
nameDev.setNameDev("dev");
nameDevMapper.insert(nameDev); if(hasException) {
throw new Exception();
}
} }

nameservice

controller代码

 package com.xy.controller;

 import com.xy.service.NameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; /**
* Created by helloworld on 2014/11/22.
*/
@Controller
public class mybatisController { @Autowired
NameService nameService; @RequestMapping(value = "/addName", method = RequestMethod.POST)
ModelMap addName(@RequestParam("hasException") boolean hasException) {
try {
nameService.addQaAndDev(hasException);
} catch (Exception e) {
e.printStackTrace();
return new ModelMap("false");
}
return new ModelMap("true");
} }

controller

将项目打成war包,命名为mybatis.war部署在tomcat上。

测试:

1.POST  http://localhost:8080/mybatis/addName.json

request parameters: hasException=false

返回:true 数据添加成功

2.POST  http://localhost:8080/mybatis/addName.json

 request parameters: hasException=true


返回:false 两个数据库数据都未添加 源码下载:http://files.cnblogs.com/files/rain-in-sun/springmvc-mybatis-atomikos.rar