seata服務端搭建和客戶端配置(使用nacos進行注冊發現,使用mysql進行數據持久化),以及過程中可能會出現的問題與解決方案


說明:

之所以只用nacos進行了注冊與發現,因為seata使用nacos后進行配置中心的化,需要往nacos中導入py腳本生成配置,還需要在服務端多加兩個配置,過程比較繁瑣,容易出問題,不太適合對這個框架理解不是很深的開發者
關於集成之后出現與mybatisplus沖突問題,插件失效,自動填充失效等問題,請看本人seata分類下另一篇文章

版本說明:

mysql 5.7
seata 1.4
springboot:2.3.7
springcloud:Hoxton.SR12
springcloudAlibaba: 2.2.6.RELEASE

服務端搭建及配置

  1. 下載seata 下載地址:下載中心 (seata.io)

  2. 上傳至虛擬機/服務器/本地

    解壓該文件:解壓后

     

     

     

  3. 進入conf目錄

     

     

     

  4. 修改registry.conf文件 

     

     

    對應配置:

    registry {
     # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
    type = "nacos"
    loadBalance = "RandomLoadBalance"
    loadBalanceVirtualNodes = 10

    nacos {
      application = "seata-server"
      serverAddr = "192.168.3.160:8848"
      group = "SEATA_GROUP"
      namespace = ""
      cluster = "default"
      username = ""
      password = ""
     }
     
    file {
      name = "file.conf"
     }
    }

    config {
     # file、nacos 、apollo、zk、consul、etcd3
    type = "file"

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

    file {
      name = "file.conf"
     }
    }

     

  5. 修改file.config文件

     

     

    對應配置:

    ## 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 = "123456"
      minConn = 5
      maxConn = 100
      globalTable = "global_table"
      branchTable = "branch_table"
      lockTable = "lock_table"
      queryLimit = 100
      maxWait = 5000
     }
    }

     

  6. 因為我們這里配置的持久化方式為mysql,在第六步中也有體現,這里需要將第六步配置的數據庫創建出來

    1. 創建數據庫庫名為seata

    2. 導入SQL腳本,腳本為:

      /*
      Navicat Premium Data Transfer

      Source Server         : Mysql3.160
      Source Server Type   : MySQL
      Source Server Version : 50732
      Source Host           : 192.168.3.160:3306
      Source Schema         : seata

      Target Server Type   : MySQL
      Target Server Version : 50732
      File Encoding         : 65001

      Date: 13/12/2021 14:33:52
      */

      SET NAMES utf8mb4;
      SET FOREIGN_KEY_CHECKS = 0;

      -- ----------------------------
      -- Table structure for branch_table
      -- ----------------------------
      DROP TABLE IF EXISTS `branch_table`;
      CREATE TABLE `branch_table`  (
       `branch_id` bigint(20) NOT NULL,
       `xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
       `transaction_id` bigint(20) NULL DEFAULT NULL,
       `resource_group_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `resource_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `branch_type` varchar(8) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `status` tinyint(4) NULL DEFAULT NULL,
       `client_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `application_data` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `gmt_create` datetime(6) NULL DEFAULT NULL,
       `gmt_modified` datetime(6) NULL DEFAULT NULL,
       PRIMARY KEY (`branch_id`) USING BTREE,
       INDEX `idx_xid`(`xid`) USING BTREE
      ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

      -- ----------------------------
      -- Records of branch_table
      -- ----------------------------

      -- ----------------------------
      -- Table structure for global_table
      -- ----------------------------
      DROP TABLE IF EXISTS `global_table`;
      CREATE TABLE `global_table`  (
       `xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
       `transaction_id` bigint(20) NULL DEFAULT NULL,
       `status` tinyint(4) NOT NULL,
       `application_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `transaction_service_group` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `transaction_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `timeout` int(11) NULL DEFAULT NULL,
       `begin_time` bigint(20) NULL DEFAULT NULL,
       `application_data` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `gmt_create` datetime NULL DEFAULT NULL,
       `gmt_modified` datetime NULL DEFAULT NULL,
       PRIMARY KEY (`xid`) USING BTREE,
       INDEX `idx_gmt_modified_status`(`gmt_modified`, `status`) USING BTREE,
       INDEX `idx_transaction_id`(`transaction_id`) USING BTREE
      ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

      -- ----------------------------
      -- Records of global_table
      -- ----------------------------

      -- ----------------------------
      -- Table structure for lock_table
      -- ----------------------------
      DROP TABLE IF EXISTS `lock_table`;
      CREATE TABLE `lock_table`  (
       `row_key` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
       `xid` varchar(96) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `transaction_id` bigint(20) NULL DEFAULT NULL,
       `branch_id` bigint(20) NOT NULL,
       `resource_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `table_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `pk` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
       `gmt_create` datetime NULL DEFAULT NULL,
       `gmt_modified` datetime NULL DEFAULT NULL,
       PRIMARY KEY (`row_key`) USING BTREE,
       INDEX `idx_branch_id`(`branch_id`) USING BTREE
      ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

      -- ----------------------------
      -- Records of lock_table
      -- ----------------------------

      SET FOREIGN_KEY_CHECKS = 1;

       

    3. 導入后樣子: 

       

       

       

  7. 至此服務端配置配置完成,cd目錄到bin目錄通過以下命令進行啟動,-h 127.0.0.1 可替換為真實的虛擬機地址,最好指定真實的,否則可能出現無法預估的錯誤

    nohup sh seata-server.sh -p 8091 -h 127.0.0.1 -m file > catalina.out 2>&1 &

客戶端配置

  1. 引入seata依賴

    <!--seata-->
    <dependency>
       <groupId>com.alibaba.cloud</groupId>
       <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
       <version>2021.1</version>
    </dependency>
    <!--mybatis-plus 因為需要替換mybatisplus的數據源,所以引入了這個依賴-->
    <dependency>
       <groupId>com.baomidou</groupId>
       <artifactId>mybatis-plus-boot-starter</artifactId>
       <scope>provided</scope>
    </dependency>
  2. 在resources下添加兩個文件,分別為file.conf和registry.conf

    registry.conf內容為 

     

     

    內容為:

    registry {
     # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
     type = "nacos"
     loadBalance = "RandomLoadBalance"
     loadBalanceVirtualNodes = 10

     nacos {
       application = "seata-server"
       serverAddr = "192.168.3.160:8848"
       group = "SEATA_GROUP"
       namespace = ""
       cluster = "default"
       username = ""
       password = ""
    }
     file {
       name = "file.conf"
    }
    }
    config {
     # file、nacos 、apollo、zk、consul、etcd3
     type = "file"
     nacos {
       serverAddr = "192.168.3.160:8848"
       namespace = ""
       group = "SEATA_GROUP"
       username = ""
       password = ""
    }
     file {
       name = "file.conf"
    }
    }

    file.conf內容為:此處需注意vgroupMapping這里進行了修改,原為vgroup_mapping,不改為駝峰會出現ip:port這個錯誤,導致項目起不來 

     

     

     

     

    內容如下:

    transport {
     # tcp udt unix-domain-socket
     type = "TCP"
     #NIO NATIVE
     server = "NIO"
     #enable heartbeat
     heartbeat = true
     #thread factory for netty
     thread-factory {
       boss-thread-prefix = "NettyBoss"
       worker-thread-prefix = "NettyServerNIOWorker"
       server-executor-thread-prefix = "NettyServerBizHandler"
       share-boss-worker = false
       client-selector-thread-prefix = "NettyClientSelector"
       client-selector-thread-size = 1
       client-worker-thread-prefix = "NettyClientWorkerThread"
       # netty boss thread size,will not be used for UDT
       boss-thread-size = 1
       #auto default pin or 8
       worker-thread-size = 8
    }
    }

    service {
     #vgroup->rgroup
     vgroupMapping.from-sys_tx_group = "default"
     #only support single node
     default.grouplist = "192.168.3.160:8091"
     #degrade current not support
     enableDegrade = false
     #disable
     disable = false
    }
    ## 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://192.168.3.160:3306/seata"
       user = "root"
       password = "123456"
       minConn = 5
       maxConn = 30
       globalTable = "global_table"
       branchTable = "branch_table"
       lockTable = "lock_table"
       queryLimit = 100
       maxWait = 5000
    }
    }

    application.yml需配置以下內容: 

     

     

    內容如下:

    spring:
     #---------------數據庫連接配置--------------
    datasource:
      type: com.alibaba.druid.pool.DruidDataSource
       # 連接url
      url: jdbc:mysql://192.168.3.160:3306/from-sys?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true
       # 驅動名稱
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: 123456
      initialSize: 5
      minIdle: 5
      maxActive: 20
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT user()
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      connection-properties: druid.stat.mergeSql:true;druid.stat.slowSqlMillis:5000
     # -------------- nacos配置---------------
    cloud:
      nacos:
        discovery:
          server-addr: 192.168.3.160:8848
      alibaba:
        seata:
          tx-service-group: ${spring.application.name}_tx_group
    seata:
    registry:
      type: nacos
      nacos:
        server-addr: 192.168.3.160:8848
        group: "SEATA_GROUP"
        namespace: ""
        username: "nacos"
        password: "nacos"
    server:
    port: 9001
    servlet:
      context-path: /sys/
  3. 配置代理數據源

     

     

    package com.from.seata.config;

    import com.alibaba.druid.pool.DruidDataSource;
    import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
    import com.baomidou.mybatisplus.core.MybatisConfiguration;
    import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
    import io.seata.rm.datasource.DataSourceProxy;
    import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;

    import javax.sql.DataSource;

    @Configuration
    @EnableConfigurationProperties({MybatisPlusProperties.class})
    public class DataSourcesProxyConfig {
       @Bean
       @ConfigurationProperties(prefix = "spring.datasource")
       public DataSource druidDataSource() {
           return new DruidDataSource();
      }
       //創建代理數據源

       @Primary//@Primary標識必須配置在代碼數據源上,否則本地事務失效
       @Bean
       public DataSourceProxy dataSourceProxy(DataSource druidDataSource) {
           return new DataSourceProxy(druidDataSource);
      }

       private MybatisPlusProperties properties;

       public DataSourcesProxyConfig(MybatisPlusProperties properties) {
           this.properties = properties;
      }

       //替換SqlSessionFactory的DataSource
       @Bean
       public MybatisSqlSessionFactoryBean sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
           // 這里必須用 MybatisSqlSessionFactoryBean 代替了 SqlSessionFactoryBean,否則 MyBatisPlus 不會生效
           MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
           mybatisSqlSessionFactoryBean.setDataSource(dataSourceProxy);
           mybatisSqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());

          mybatisSqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                  .getResources("classpath:/mapper/**/*.xml")); //注意:!!!!這個如果寫的有sql,需有該配置,try cach以下,不配置造成sql找不到,打開不捕獲異常的化,沒sql會報錯

           MybatisConfiguration configuration = this.properties.getConfiguration();
           if(configuration == null){
               configuration = new MybatisConfiguration();
          }
           mybatisSqlSessionFactoryBean.setConfiguration(configuration);
           return mybatisSqlSessionFactoryBean;
      }
    }

    至此seata的分布式事務就配置完成了,可以優化為seata單獨抽成一個模塊,當我們服務需要使用分布式事務時候,引入seata模塊的依賴,進行相同的配file,registry,yml配置即可,只需修改以下下內容,其他配置不變即可 

     

     

     

你可能遇到的bug:

  1. 1.Failed to get available servers: endpoint format should like ip:port

    file.conf中的vgroupMapping你用的可能是vgroup_mapping
  2. 0101 can not connect to 127.0.0.1:8091 cause:can not register RM,err:can not connect to services-server. nacos注冊發現的情況下:則是由於yml里面沒有配置seata的注冊發現造成的

     

     

  3. 0101 can not connect to 遠程地址:8091 cause:can not register RM,err:can not connect to services-server.

    由於你的啟動seata服務時候沒有指定IP端口造成的,導致你注冊到nacos上的seata服務地址跟你客戶端預想的seata地址不一致造成的,修改為真實的你的服務器地址 

     

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM