springmvc+mybatis多数据源分布式事务管理

来源:互联网 发布:python opengl 教程 编辑:程序博客网 时间:2024/05/16 19:20

目录

    • springmvcmybatis多数据源分布式事务管理
    • pom依赖
    • jtaproperties
    • 配置数据源
    • 配置SQLSessionFactory
    • 配置MapperScanner
    • 配置Jta事务
    • 实体
    • dao
    • XML
    • service
    • Junit测试
    • 完结

springmvc+mybatis多数据源分布式事务管理

    最近项目用到spring多数据源以进行数据整合,可是配置上事务时,发现数据源不能进行切换,原因是因为事务是在connection层面管理的,启用事务后,一个事务内部的connection是复用的,所以就算AOP切了数据源字符串,但是数据源并不会被真正修改,所以决定使用atomikos进行分布式事务的管理。

pom依赖

<dependency>    <groupId>com.atomikos</groupId>    <artifactId>transactions-jdbc</artifactId>    <version>3.9.1</version></dependency><dependency>    <groupId>javax.transaction</groupId>    <artifactId>jta</artifactId>    <version>1.1</version></dependency><dependency>    <groupId>cglib</groupId>    <artifactId>cglib-nodep</artifactId>    <version>3.2.4</version></dependency>

jta.properties

把此配置文件放入classpath路径 项目启动会自动加载 不需进行配置
com.atomikos.icatch.service=com.atomikos.icatch.standalone.UserTransactionServiceFactorycom.atomikos.icatch.console_file_name = tm.out   com.atomikos.icatch.log_base_name = tmlog   com.atomikos.icatch.tm_unique_name = com.atomikos.spring.jdbc.tm   com.atomikos.icatch.console_log_level = INFO  

配置数据源

    为了测试这里配置2个数据源,大家可按自己项目情况配置。
<property name="uniqueResourceName" value="ds1"/>
    注意当配置多个数据源时uniqueResourceName的value不能重复
<bean id="dataSource1" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-               method="init" destroy-method="close">    <property name="uniqueResourceName" value="ds1"/>    <property name="xaDataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"/>    <property name="xaProperties">        <props>            <prop key="url">jdbc:mysql://localhost/test</prop>            <prop key="user">root</prop>            <prop key="password">123456</prop>        </props>    </property>    <property name="minPoolSize" value="10" />    <property name="maxPoolSize" value="100" />    <property name="borrowConnectionTimeout" value="30" />    <property name="testQuery" value="select 1" />    <property name="maintenanceInterval" value="60" /></bean><bean id="dataSource2" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">    <property name="uniqueResourceName" value="ds2"/>    <property name="xaDataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"/>    <property name="xaProperties">        <props>            <prop key="url">jdbc:mysql://localhost/smart-sso</prop>            <prop key="user">root</prop>            <prop key="password">123456</prop>        </props>    </property>    <property name="minPoolSize" value="10" />    <property name="maxPoolSize" value="100" />    <property name="borrowConnectionTimeout" value="30" />    <property name="testQuery" value="select 1" />    <property name="maintenanceInterval" value="60" /></bean>

配置SQLSessionFactory

    指定mapper文件和实体所在路径
<bean id="sqlSessionFactory1" class="org.mybatis.spring.SqlSessionFactoryBean">    <property name="dataSource" ref="dataSource1"/>    <property name="mapperLocations" value="classpath:mapper/*.xml"/>    <property name="typeAliasesPackage" value="com.fk.entity"/></bean><bean id="sqlSessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean">    <property name="dataSource" ref="dataSource2"/>    <property name="mapperLocations" value="classpath:mapper/*.xml"/>    <property name="typeAliasesPackage" value="com.fk.entity"/></bean>

配置MapperScanner

    指定dao文件所在包 并指定所用SQlSessionFactory
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">    <property name="basePackage" value="com.fk.mapperOne" />    <property name="sqlSessionFactory" ref="sqlSessionFactory1"/></bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">    <property name="basePackage" value="com.fk.mapperTwo" />    <property name="sqlSessionFactory" ref="sqlSessionFactory2"/></bean>

配置Jta事务

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">    <property name="transactionManager">        <bean class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close">            <property name="forceShutdown" value="true"/>        </bean>    </property>    <property name="userTransaction">        <bean class="com.atomikos.icatch.jta.UserTransactionImp"/>    </property></bean>
    最后加上声明式注解支持
    <tx:annotation-driven/>
    数据源和事务配置已经完成,接下来就是测试分布式事务是否可用了。

实体

为了测试方便 这里2个数据源使用的是一个实体
public class Student {    private Integer id;    private String name;    private Integer age;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }}

dao

    这里两个mapper分别在配置MapperScanner配置的包体里
package com.fk.mapperOne;import com.fk.entity.Student;import org.springframework.stereotype.Repository;@Repositorypublic interface StudentOneMapper {    void insert(Student student);}
package com.fk.mapperTwo;import com.fk.entity.Student;import org.springframework.stereotype.Repository;@Repositorypublic interface StudentTwoMapper {    void insert(Student student);}

XML

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.fk.mapperOne.StudentOneMapper" >    <insert id="insert" parameterType="com.fk.entity.Student">        insert into student(id,name,age) values (#{id},#{name},#{age})    </insert></mapper>
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.fk.mapperTwo.StudentTwoMapper" >    <insert id="insert" parameterType="com.fk.entity.Student">        insert into student(id,name,age) values (#{id},#{name},#{age})    </insert></mapper>

service

package com.fk.service;

import com.fk.entity.Student;
import com.fk.mapperOne.StudentOneMapper;
import com.fk.mapperTwo.StudentTwoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentServiceImpl {

@Autowiredprivate StudentOneMapper studentOneMapper;@Autowiredprivate StudentTwoMapper studentTwoMapper;@Transactionalpublic void insert() throws Exception{    Student student = new Student();    student.setId(1);    student.setName("Nancy");    student.setAge(12);    studentOneMapper.insert(student);    student = new Student();    student.setId(1);    student.setName("Tom");    student.setAge(2);    studentTwoMapper.insert(student);}

}

Junit测试

接下来使用junit进行测试
import com.fk.service.StudentServiceImpl;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:/spring/spring-mvc.xml",        "classpath:/spring/spring-mybatis.xml"})public class StudentJunit {    @Autowired    private StudentServiceImpl studentService;    @Test    public void TestInsert(){        try {            studentService.insert();        } catch (Exception e) {            e.printStackTrace();        }    }}
先测试下是否能插入数据

这里写图片描述

可以看到2个数据库里都已经插入一条数据接下来在测试下异常是否会回滚
@Transactional    public void insert() throws Exception{        Student student = new Student();        student.setId(2);        student.setName("Nancy");        student.setAge(12);        studentOneMapper.insert(student);        student = new Student();        student.setId(1);        student.setName("Tom");        student.setAge(2);        studentTwoMapper.insert(student);    }
    将第一个插入实体的ID加1,保持第二个实体不变,因为表里有设置主键,这样第二条插入时,会出现主键重复异常,以此来测试第一条插入语句是否会回滚。

这里写图片描述

如我们所愿,主键重复,接下来看下数据是否有插入

这里写图片描述

yes!数据没有插入,则证明事务已回滚了。

完结

分布式事务的内容就是这些了,由于本人初次接触分布式事务,有不足之处还请谅解并指出,谢谢! [完整Demo](http://git.oschina.net/monsterjava/fk_demo/tree/feature_fk/)
阅读全文
0 0
原创粉丝点击