Spring分布式事务- 三种实现方式(Spring+JTA)

分布式事务是指事务的参与者、支持事务的服务器、资源管理器以及事务管理器分别位于分布系统的不同节点之上,在两个或多个网络计算机资源上访问并且更新数据,将两个或多个网络计算机的数据进行的多次操作作为一个整体进行处理。如不同银行账户之间的转账。

对于在项目中接触到JTA,大部分的原因是因为在项目中需要操作多个数据库,同时,可以保证操作的原子性,保证对多个数据库的操作一致性。
项目结构图Spring分布式事务- 三种实现方式(Spring+JTA)_第1张图片
1、pom.xml




    4.0.0
    war
    jta
    com.roden.jta
    jta
    0.0.1-SNAPSHOT   

      
        
            junit
            junit
            4.12
            
            test
                       
        
            org.springframework
            spring-test
            3.2.14.RELEASE
            provided
        

        
            mysql
            mysql-connector-java
            5.1.34
               
        
            com.atomikos
            transactions-jdbc
            3.9.3
           
        
            javax.transaction
            jta
            1.1
           

        
        
            javax
            javaee-api
            7.0
               
        
            org.springframework
            spring-context
            3.2.16.RELEASE
               
        
            org.springframework
            spring-jdbc
            3.2.16.RELEASE
               

    

2、applicationContext.xml


   

    
    
        master xa datasource
        
            master
        
        
        
            
                root
                
                jdbc:mysql://127.0.0.1:3306/master
            
             
         
    

    
        slave xa datasource
        
            slave
        
        
            com.mysql.jdbc.jdbc2.optional.MysqlXADataSource
        
        
            
                root
                
                jdbc:mysql://127.0.0.1:3306/slave
            
             
        
    

    
    
        UserTransactionManager
        
            true
        
    

    
        
    

    
    
        
            
        
        
            
        
    

    
    
        
            
        
      

    
        
            
        
    

    
        
            
        
    

       
      
       


3、java类
package com.roden.jta.controller;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.roden.jta.service.TestService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@Controller
public class TestController {   
    @Autowired
    private TestService testService;
    //MySQL的数据库引擎必须是InnoDB,否则无法回滚
    @Test
    public void test(){
        testService.test();
    }
    @Test
    public void test2(){
        testService.update();
    }

    @Test
    public void test3(){
        testService.test3();
    }
}
package com.roden.jta.service;

public interface TestService {
    public String test();
    public String update();

     public void test3();
}
package com.roden.jta.service.impl;

import javax.annotation.Resource;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.jta.JtaTransactionManager;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.roden.jta.dao.TestMasterDao;
import com.roden.jta.dao.TestSlaveDao;
import com.roden.jta.service.TestService;
@Service
public class TestServiceImpl implements TestService{
    @Resource(name = "springTransactionManager")
    private JtaTransactionManager txManager;
    @Autowired
    private TestMasterDao testMasterDao;
    @Autowired
    private TestSlaveDao testSlaveDao;  

    @Resource(name = "transactionTemplate")
    private TransactionTemplate transactionTemplate;  
    //编程式
    @Override
    public String test() {
         UserTransaction userTx = txManager.getUserTransaction(); 
         try {               
             userTx.begin();     
             testMasterDao.master(); 
             testSlaveDao.slave();    
             int a=1/0;
             System.out.println(a);
             userTx.commit();
         } catch (Exception e) {
             System.out.println("捕获到异常,进行回滚" + e.getMessage());
             e.printStackTrace();
             try {
                 userTx.rollback();
             } catch (IllegalStateException e1) {
                System.out.println("IllegalStateException:" + e1.getMessage());
             } catch (SecurityException e1) {
                 System.out.println("SecurityException:" + e1.getMessage());
             } catch (SystemException e1) {
                 System.out.println("SystemException:" + e1.getMessage());
             }              
         }
        return null;
    }
    //声明式
    @Override
    @Transactional
    public String update(){
         testMasterDao.master();        
         testSlaveDao.slave();   
         //int a=1/0;
         //System.out.println(a);
        return null;
    }
    //事务模板方式
    @Override
     public void test3() {  

            transactionTemplate.execute(new TransactionCallbackWithoutResult(){  
                @Override  
                protected void doInTransactionWithoutResult(TransactionStatus status) {  
                    try {  
                         testMasterDao.master();        
                         testSlaveDao.slave();   
                         int a=1/0;
                        System.out.println(a);
                    } catch (Exception ex) {  
                        // 通过调用 TransactionStatus 对象的 setRollbackOnly() 方法来回滚事务。  
                        status.setRollbackOnly();  
                        ex.printStackTrace();  
                    }  
                }  
            });         


               /* 
                //有返回值的回调
                 Object obj=transactionTemplate.execute(new TransactionCallback(){
                    @Override
                    public Object doInTransaction(TransactionStatus status) {

                        return 1;
                    }  
                });  */
        }  


}
package com.roden.jta.dao;

public interface TestMasterDao {
    public String master();
    public String update();
}
package com.roden.jta.dao;

public interface TestSlaveDao {
    public String slave();
}
package com.roden.jta.dao.impl;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.roden.jta.dao.TestMasterDao;
@Repository
public class TestMasterDaoImpl implements TestMasterDao{

    @Resource(name="masterJdbcTemplate")
    JdbcTemplate masterJdbcTemplate;
    @Override
    public String master() {
        masterJdbcTemplate.execute("update teacher set name='master' where id=1");
        return "success";
    }

    @Override
    public String update() {
        masterJdbcTemplate.execute("update teacher set name='8' where id=1");
        System.out.println("update");
        masterJdbcTemplate.execute("fff teacher set name=''6' where id=1");

        return null;
    }

}
package com.roden.jta.dao.impl;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.roden.jta.dao.TestSlaveDao;
@Repository
public class TestSlaveDaoImpl implements TestSlaveDao{

    @Resource(name="slaveJdbcTemplate")
    JdbcTemplate slaveJdbcTemplate;
    @Override
    public String slave() {
        slaveJdbcTemplate.execute("update student set name='slave' where id=1");            
        return "success";
    }   

}

数据源详细参数配置

    
     <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="logWriter" value="60"/>
        <property name="testQuery">
            <value>select 1value>
        property>

    bean> 
    
    <bean id="dataSource" parent="abstractXADataSource">
         
        <property name="uniqueResourceName" value="mysql/sitestone" />
        <property name="xaDataSourceClassName"
            value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" />
        <property name="xaProperties">
            <props>
                <prop key="URL">${jdbc.url}prop>
                <prop key="user">${jdbc.username}prop>
                <prop key="password">${jdbc.password}prop>
            props>
        property>
    bean>

    
    <bean id="dataSourceB" parent="abstractXADataSource">
        
        <property name="uniqueResourceName" value="mysql/sitesttwo" />
        <property name="xaDataSourceClassName"
            value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" />
        <property name="xaProperties">
            <props>
                <prop key="URL">${jdbca.url}prop>
                <prop key="user">${jdbca.username}prop>
                <prop key="password">${jdbca.password}prop>
            props>
        property>
    bean>

你可能感兴趣的:(Java)