欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot 整合 Atomikos 实现分布式多数据源事务管理器

程序员文章站 2024-01-09 23:09:28
一个简单的demo介绍 随着项目越做越大,模块拆分、数据库拆分,实际开发中,数据库节点会被分割在多个物理机上,一个业务逻辑中可能包含多个数据库表之间的数据插入,需要保证事务的一致性、原子性,此时就需要用到分布式事务管理。工程结构以下为相关代码数据源1package com.wang.learn.jtaatomikos.config;import lombok.Data;import org.springframework.boot.context.properties.....

一个简单的demo

介绍

  随着项目越做越大,模块拆分、数据库拆分,实际开发中,数据库节点会被分割在多个物理机上,一个业务逻辑中可能包含多个数据库表之间的数据插入,需要保证事务的一致性、原子性,此时就需要用到分布式事务管理。

工程结构

SpringBoot 整合 Atomikos  实现分布式多数据源事务管理器

以下为相关代码

数据源1

package com.wang.learn.jtaatomikos.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * description: DB1Config
 * date: 2020/11/28 12:06
 *
 * @author: http://www.itdream.site
 * version: 1.0
 */
@Configuration
@ConfigurationProperties(prefix = "spring.datasource.db1")
@Data
public class DB1Config {
    private  String username;
    private String password;
    private String jdbcUrl;
}

数据源2

package com.wang.learn.jtaatomikos.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * description: DB2Config
 * date: 2020/11/28 12:07
 *
 * @author: http://www.itdream.site
 * version: 1.0
 */
@Configuration
@ConfigurationProperties(prefix = "spring.datasource.db2")
@Data
public class DB2Config {
    private  String username;
    private String password;
    private String jdbcUrl;
}

sql会话配置1

package com.wang.learn.jtaatomikos.config;

import com.mysql.cj.jdbc.MysqlXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * description: DbSessionFactory1
 * date: 2020/11/28 12:08
 *
 * @author: http://www.itdream.site
 * version: 1.0
 */
@Configuration
@MapperScan(basePackages = {"com.wang.learn.jtaatomikos.mapper.db1"}, sqlSessionFactoryRef = "sqlSessionFactoryDb1")
public class DbSessionFactory1 {

    @Bean(name = "db1")
    public DataSource businessDbDataSource(@Qualifier("DB1Config") DB1Config db1Conf) throws SQLException {
        MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
        mysqlXaDataSource.setUrl(db1Conf.getJdbcUrl());
        mysqlXaDataSource.setPassword(db1Conf.getPassword());
        mysqlXaDataSource.setUser(db1Conf.getUsername());
        mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);

        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        xaDataSource.setXaDataSource(mysqlXaDataSource);
        xaDataSource.setUniqueResourceName("db1");
        return xaDataSource;
    }

    @Bean(name="sqlSessionFactoryDb1")
    public SqlSessionFactory sqlSessionFactoryDb1(@Qualifier("db1")DataSource DataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(DataSource);
        return factoryBean.getObject();
    }

    @Bean(name="sqlSessionTemplateDb1")
    public SqlSessionTemplate sqlSessionTemplateDb1(@Qualifier("sqlSessionFactoryDb1") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

sql会话配置2

package com.wang.learn.jtaatomikos.config;

import com.mysql.cj.jdbc.MysqlXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * description: DbSessionFactory2
 * date: 2020/11/28 14:11
 *
 * @author: http://www.itdream.site
 * version: 1.0
 */
@Configuration
@MapperScan(basePackages = {"com.wang.learn.jtaatomikos.mapper.db2"}, sqlSessionFactoryRef = "sqlSessionFactoryDb2")
public class DbSessionFactory2 {

    @Bean(name = "db2")
    public DataSource newhomeDbDataSource(@Qualifier("DB2Config") DB2Config db2Conf) throws SQLException {
        MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
        mysqlXaDataSource.setUrl(db2Conf.getJdbcUrl());
        mysqlXaDataSource.setPassword(db2Conf.getPassword());
        mysqlXaDataSource.setUser(db2Conf.getUsername());
        mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);

        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        xaDataSource.setXaDataSource(mysqlXaDataSource);
        xaDataSource.setUniqueResourceName("db2");
        return xaDataSource;
    }


    @Bean(name="sqlSessionFactoryDb2")
    public SqlSessionFactory sqlSessionFactoryDb2(@Qualifier("db2")DataSource DataSource ) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(DataSource);
        return factoryBean.getObject();
    }

    @Bean(name="sqlSessionTemplateDb2")
    public SqlSessionTemplate sqlSessionTemplateDb2(@Qualifier("sqlSessionFactoryDb2") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

db1的mapper

package com.wang.learn.jtaatomikos.mapper.db1;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;

/**
 * description: OrderMapper
 * date: 2020/11/28 14:13
 *
 * @author: http://www.itdream.site
 * version: 1.0
 */
public interface OrderMapper {
    @Insert("INSERT INTO orders(id, name) VALUES(#{id}, #{name})")
    int insert(@Param("id") String id, @Param("name") String name);
}

db2的mapper

package com.wang.learn.jtaatomikos.mapper.db2;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;

/**
 * description: OrderDetailMapper
 * date: 2020/11/28 14:16
 *
 * @author: http://www.itdream.site
 * version: 1.0
 */
public interface OrderDetailMapper {

    @Insert("INSERT INTO order_details(id, orderId) VALUES(#{id}, #{orderId})")
    int insert(@Param("id") int id, @Param("orderId") String orderId);

}

service

package com.wang.learn.jtaatomikos.service;

import com.wang.learn.jtaatomikos.mapper.db2.OrderDetailMapper;
import com.wang.learn.jtaatomikos.mapper.db1.OrderMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * description: OrderServiceImpl
 * date: 2020/11/28 14:16
 *
 * @author: http://www.itdream.site
 * version: 1.0
 */

@Service
public class OrderServiceImpl {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Transactional
    public String insertDbaAndDbB(boolean flag) {
        String orderId = UUID.randomUUID().toString();
        orderMapper.insert(orderId, "重入门到放弃");
        if(flag){
            System.out.println(1 / 0);
        }
        orderDetailMapper.insert(1, orderId);
        return "success";
    }

}

controller

package com.wang.learn.jtaatomikos.controller;

import com.wang.learn.jtaatomikos.service.OrderServiceImpl;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * description: AtomikosController
 * date: 2020/11/28 14:14
 *
 * @author: http://www.itdream.site
 * version: 1.0
 */

@RestController
public class AtomikosController {


    @Resource
    private OrderServiceImpl orderService;

    @RequestMapping("/test")
    public Object test(@RequestParam boolean flag){

        String msg = "insert data successful";
        try {
            orderService.insertDbaAndDbB(flag);
        } catch (Exception e) {
            msg = "data rollback";
            e.printStackTrace();

        }
        return msg;
    }
}

配置文件

spring:
  application: jta-atomikos
  datasource:
    db1:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/orders?useSSL=false&serverTimezone=GMT%2b8&characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
      username: root
      password: 123
    db2:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/orderdetails?useSSL=false&serverTimezone=GMT%2b8&characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
      username: root
      password: 123

server:
  port: 8004

 

创建两个数据库,两张表

create table orders(
id varchar(40),
name varchar(25)
);
create table order_details(
id int,
orderId  varchar(40)
);

测试:  http://localhost:8004/test?flag=true

本文地址:https://blog.csdn.net/SpringHASh/article/details/110276099

相关标签: java