springcloud + Seata1.3.0 + nacos1.3.2 分布式事务集成

springcloud + Seata1.3.0 + nacos1.3.2 分布式事务集成

  • 1.安装seata
    • config.txt配置文件
    • seata库中的表
    • 需要事务控制的数据库中创建表
  • 2.引入包
  • 3.项目resources目录创建registry.conf
  • 4.项目resources目录创建file.conf
  • 5.bootstrap.yml 中配置
  • 6.启动类排除DataSourceAutoConfiguration.class
  • 7.数据源配置 DataSourceConfig
  • 8.配置全局异常

1.安装seata

查看文章

config.txt配置文件

service.vgroupMapping.my_test_tx_group=default
store.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
store.db.user=root
store.db.password=111111
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000

seata库中的表

CREATE TABLE `branch_table` (
  `branch_id` bigint(20) NOT NULL,
  `xid` varchar(128) COLLATE utf8mb4_hungarian_ci NOT NULL,
  `transaction_id` bigint(20) DEFAULT NULL,
  `resource_group_id` varchar(32) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `resource_id` varchar(256) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `lock_key` varchar(128) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `branch_type` varchar(8) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `status` tinyint(4) DEFAULT NULL,
  `client_id` varchar(64) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `application_data` varchar(2000) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `gmt_create` datetime DEFAULT NULL,
  `gmt_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`branch_id`),
  KEY `idx_xid` (`xid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_hungarian_ci;

CREATE TABLE `global_table` (
  `xid` varchar(128) COLLATE utf8mb4_hungarian_ci NOT NULL,
  `transaction_id` bigint(20) DEFAULT NULL,
  `status` tinyint(4) NOT NULL,
  `application_id` varchar(32) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `transaction_service_group` varchar(32) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `transaction_name` varchar(128) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `timeout` int(11) DEFAULT NULL,
  `begin_time` bigint(20) DEFAULT NULL,
  `application_data` varchar(2000) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `gmt_create` datetime DEFAULT NULL,
  `gmt_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`xid`),
  KEY `idx_gmt_modified_status` (`gmt_modified`,`status`),
  KEY `idx_transaction_id` (`transaction_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_hungarian_ci;

CREATE TABLE `lock_table` (
  `row_key` varchar(128) COLLATE utf8mb4_hungarian_ci NOT NULL,
  `xid` varchar(96) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `transaction_id` mediumtext COLLATE utf8mb4_hungarian_ci,
  `branch_id` mediumtext COLLATE utf8mb4_hungarian_ci,
  `resource_id` varchar(256) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `table_name` varchar(32) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `pk` varchar(36) COLLATE utf8mb4_hungarian_ci DEFAULT NULL,
  `gmt_create` datetime DEFAULT NULL,
  `gmt_modified` datetime DEFAULT NULL,
  PRIMARY KEY (`row_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_hungarian_ci;

需要事务控制的数据库中创建表

CREATE TABLE `undo_log` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `branch_id` bigint(20) NOT NULL,
  `xid` varchar(100) NOT NULL,
  `context` varchar(128) NOT NULL,
  `rollback_info` longblob NOT NULL,
  `log_status` int(11) NOT NULL,
  `log_created` datetime NOT NULL,
  `log_modified` datetime NOT NULL,
  `ext` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.引入包

		<!-- 分布式事务 seata -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.seata</groupId>
                    <artifactId>seata-all</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.seata</groupId>
            <artifactId>seata-all</artifactId>
            <version>1.3.0</version>
        </dependency>

3.项目resources目录创建registry.conf

registry {
  type = "nacos"
  nacos {
      application = "seata-server"
      serverAddr = "127.0.0.1:8848"
      group = "SEATA_GROUP"
      namespace = ""
      cluster = "default"
      username = ""
      password = ""
    }
}

config {
  type = "nacos"
  nacos {
      serverAddr = "127.0.0.1:8848"
      namespace = ""
      group = "SEATA_GROUP"
      username = ""
      password = ""
    }
}

4.项目resources目录创建file.conf

## transaction log store, only used in seata-server
store {
  ## store mode: file、db、redis
  mode = "db"

  ## database store property
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
    datasource = "druid"
    ## mysql/oracle/postgresql/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://127.0.0.1:3306/seata"
    user = "root"
    password = "111111"
    minConn = 5
    maxConn = 30
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }
}

5.bootstrap.yml 中配置

spring:
	cloud:
		alibaba:
      		seata:
        		# 该属性需要与前面config.txt文件中的service.vgroupMapping后的值保持一致
	        	tx-service-group: my_test_tx_group

#seata配置
seata:
  enabled: true
  application-id: ${service.name}-seate-service
  enable-auto-data-source-proxy: true
  config:
    type: nacos
    nacos:
      serverAddr: 127.0.0.1:8848
      # 分组需和seate分组一致,这个值未生效, 在nacos中依然为DEFAULT_GROUP, 待检查原因
      group: SEATA_GROUP
      namespace:
      username:
      password:
  registry:
    type: nacos
    nacos:
      # seata 在nacos中的服务名
      application: seata-server
      serverAddr: 127.0.0.1:8848
      # 分组需和seate分组一致
      group: SEATA_GROUP
      namespace:
      username:
      password:

6.启动类排除DataSourceAutoConfiguration.class

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
public class ServiceExampleApplication {
     

    public static void main(String[] args) {
     
        SpringApplication.run(ServiceExampleApplication.class, args);
    }

}

7.数据源配置 DataSourceConfig

package com.leo.mgt.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.unionbigdata.common.config.MyMetaObjectHandler;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 *  数据源配置
 *
 *  @Author Leo
 *  @Date 2020/9/3 18:15
 */
@Configuration
@MapperScan(basePackages = DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfig {
     

    @Autowired
    private MyMetaObjectHandler myMetaObjectHandler;

    /** dao 扫描路径 */
    static final String PACKAGE = "com.unionbigdata.*.mapper";

    /** Mapper 扫描路径 */
    static final String MAPPER_LOCATION = "classpath:mapper/*.xml";

    @Bean(name = "dataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSource dataSource() {
     
        return new DruidDataSource();
    }

    @Bean(name = {
     "dataSourceProxy"})
    public DataSourceProxy dataSourceProxy(@Qualifier("dataSource") DataSource dataSource) {
     
        return new DataSourceProxy(dataSource);
    }

    @Bean(name = "sqlSessionFactory")
    @Primary
    public SqlSessionFactory initSqlSessionFactory(@Qualifier("dataSourceProxy") DataSourceProxy dataSourceProxy) throws Exception {
     
        //全局配置,配置填充器
        GlobalConfig globalConfig  = new GlobalConfig();
        globalConfig.setMetaObjectHandler(myMetaObjectHandler);

        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSourceProxy);
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        // 分页插件
        sqlSessionFactory.setPlugins(new PaginationInterceptor());
        sqlSessionFactory.setGlobalConfig(globalConfig);
        return sqlSessionFactory.getObject();
    }

    @Bean(name = "transactionManager")
    @Primary
    public DataSourceTransactionManager initDataSourceTransactionManager(@Qualifier("dataSourceProxy") DataSourceProxy dataSourceProxy) {
     
        return new DataSourceTransactionManager(dataSourceProxy);
    }

}

8.配置全局异常

package com.leo.mgt.exception;

import com.leo.common.vo.Result;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 *  TODO
 *
 *  @Author Leo
 *  @Date 2020/9/4 18:36
 */
@RestControllerAdvice
@Slf4j
public class ControllerExceptionHandler {
     

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
     
        log.info("分布式事务id ---> " + RootContext.getXID());
        if (!StringUtils.isBlank(RootContext.getXID())){
     
            try {
     
                GlobalTransactionContext.reload(RootContext.getXID()).rollback();
            } catch (TransactionException transactionException) {
     
                log.error("分布式事务回滚错误:", transactionException);
            }
        }
        log.error("系统异常:", e);
        return Result.fail(e.getMessage());
    }

}

你可能感兴趣的:(springcloud,seata1.3.0,nacos1.3.2,java)