使用docker-compose安装seata-server,mysql8引擎,nacos作为注册和配置中心(原创可用)

一、使用docker-compose安装seata-server,mysql8引擎,nacos作为注册和配置中心

官方默认的mysql5的driver替换成了mysql8的driver,使用了nacos作为seata-server的注册中心配置中心。下面记录一下我的操作步骤:

1.首先咱们先把seata的项目通过git给下载到本地。seata github地址

  • 下载config.txt
  • 下载nacos-config.sh

2.修改config.txt配置文件

修改config.txt

注意:大多数小伙伴只需要修改以下几个参数,其他参数可暂时不改

#tx_group:自定义名字,很重要,与项目配置文件的tx-service-group一一对应
service.vgroupMapping.tx_group=default
#seata的ip+端口
service.default.grouplist=192.168.2.64:8091

# 修改存储模式为数据库存储
store.mode=db
# 指定数据库为mysql,其他数据库类型根据自身情况修改
store.db.dbType=mysql
# 指定引擎,mysql8以下为com.mysql.jdbc.Driver,mysql8为com.mysql.cj.jdbc.Driver
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://{ip}:3306/{db_name}?useUnicode=true
store.db.user={db_user}
store.db.password={db_password}

3.将修改好的config.txt配置添加到nacos配置中心

将config.txt文件放到nacos-config.sh文件所在目录的上一级目录(nacos-config.sh不作任何修改)

sh nacos-config.sh -h {nacos服务的ip} -u {nacos用户名} -w {nacos密码}

4.下载mysql8的引擎

mysql-connector-java-8.0.21.jar

第7步用到

5.编写registry.conf

第7步用到

这个文件的目的就是配置seata-server服务从nacos上读取第3步上传上去的配置,并且把自己注册到nacos的服务列表中去

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  # 指定注册中心为nacos
  type = "nacos"

  nacos {
    serverAddr = "{nacos服务的ip}:{nacos服务的端口}"
    namespace = ""
    cluster = "default"
    username="{username}"
    password="{password}"
  }
}

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

  nacos {
    serverAddr = "{nacos服务的ip}:{nacos服务的端口}"
    namespace = ""
    username="{username}"
    password="{password}"
  }
}

6.准备初始化数据库

创建第三步配置的数据库,执行下列sql

-- the table to store GlobalSession data
drop table if exists `global_table`;
create table `global_table` (
  `xid` varchar(128)  not null,
  `transaction_id` bigint,
  `status` tinyint not null,
  `application_id` varchar(32),
  `transaction_service_group` varchar(32),
  `transaction_name` varchar(128),
  `timeout` int,
  `begin_time` bigint,
  `application_data` varchar(2000),
  `gmt_create` datetime,
  `gmt_modified` datetime,
  primary key (`xid`),
  key `idx_gmt_modified_status` (`gmt_modified`, `status`),
  key `idx_transaction_id` (`transaction_id`)
);

-- the table to store BranchSession data
drop table if exists `branch_table`;
create table `branch_table` (
  `branch_id` bigint not null,
  `xid` varchar(128) not null,
  `transaction_id` bigint ,
  `resource_group_id` varchar(32),
  `resource_id` varchar(256) ,
  `lock_key` varchar(128) ,
  `branch_type` varchar(8) ,
  `status` tinyint,
  `client_id` varchar(64),
  `application_data` varchar(2000),
  `gmt_create` datetime,
  `gmt_modified` datetime,
  primary key (`branch_id`),
  key `idx_xid` (`xid`)
);

-- the table to store lock data
drop table if exists `lock_table`;
create table `lock_table` (
  `row_key` varchar(128) not null,
  `xid` varchar(96),
  `transaction_id` long ,
  `branch_id` long,
  `resource_id` varchar(256) ,
  `table_name` varchar(32) ,
  `pk` varchar(36) ,
  `gmt_create` datetime ,
  `gmt_modified` datetime,
  primary key(`row_key`)
);

7.编写docker-compose.yaml文件

version: "3.2"
services:
    # 分布式事务服务
    seata-server:
        image: seataio/seata-server:1.2.0
        ports:
            - "8091:8091"
        environment:
            #宿主机ip
            - SEATA_IP=192.168.2.64
            - SEATA_PORT=8091
            - STORE_MODE=db
        volumes:
            # 第5步编写的registry.conf
            - "./config/registry.conf:/seata-server/resources/registry.conf"
            # 第4步下载的mysql8引擎jar包
            - "./mysql-connector-java-8.0.21.jar:/seata-server/libs/mysql-connector-java-8.0.21.jar"
            # 日志文件夹
            - "./logs:/root/logs/seata"

8.启动seata-server服务

docker-compose up -d

查看nacos服务里是否启动成功

二、spring cloud alibaba集成seata、openfeign、mybatisplus

seata 依赖对版本特别敏感,版本不一致会有各种问题,要严格按照alibaba给的参考建议配置 ,以下配置基于seata1.2版本集成,不能低于此版本,会有各种问题。alibaba版本依赖关系

1、添加依赖

<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alibaba-seataartifactId>
dependency>
<dependency>
    <groupId>io.seatagroupId>
    <artifactId>seata-spring-boot-starterartifactId>
    <version>1.2.0version>
dependency>

2、添加数据源配置

1.2.0以上版本只需要配置数据源即可。每个参与分布式事务的服务都要加

package cn.zhenghe.crm.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @Description:
 * @Author: ckk
 * @CreateDate: 2020/12/4 18:36
 */
@Configuration
public class SeataConfiguration {

    //Hikari数据源配置
    /*@Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public HikariDataSource hikariDataSource() {
        HikariDataSource hikariDataSource = new HikariDataSource();
        return hikariDataSource;
    }*/

    //Druid数据源配置
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }

}

3、在resources目录下都配置两个文件

每个参与分布式事务的服务都要加

(1)、file.conf

transport {
  # tcp, unix-domain-socket
  type = "TCP"
  #NIO, NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  # the client batch send request enable
  enableClientBatchSendRequest = true
  #thread factory for netty
  threadFactory {
    bossThreadPrefix = "NettyBoss"
    workerThreadPrefix = "NettyServerNIOWorker"
    serverExecutorThread-prefix = "NettyServerBizHandler"
    shareBossWorker = false
    clientSelectorThreadPrefix = "NettyClientSelector"
    clientSelectorThreadSize = 1
    clientWorkerThreadPrefix = "NettyClientWorkerThread"
    # netty boss thread size
    bossThreadSize = 1
    #auto default pin or 8
    workerThreadSize = "default"
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}
service {
  # 自定义事务组名称 tx_group,需要与服务端一致
  vgroupMapping.tx_group = "default"
  # 仅在registry.type = file时才支持,请不要设置多个地址,这里配置 Seata Server 的 IP 和 端口
  default.grouplist = "192.168.2.64:8091"
  #degrade, current not support
  enableDegrade = false
  #disable seata
  disableGlobalTransaction = false
}

client {
  rm {
    asyncCommitBufferLimit = 10000
    lock {
      retryInterval = 10
      retryTimes = 30
      retryPolicyBranchRollbackOnConflict = true
    }
    reportRetryCount = 5
    tableMetaCheckEnable = false
    reportSuccessEnable = false
    sagaBranchRegisterEnable = false
  }
  tm {
    commitRetryCount = 5
    rollbackRetryCount = 5
    defaultGlobalTransactionTimeout = 60000
    degradeCheck = false
    degradeCheckPeriod = 2000
    degradeCheckAllowTimes = 10
  }
  undo {
    dataValidation = true
    onlyCareUpdateColumns = true
    logSerialization = "jackson"
    logTable = "undo_log"
  }
}
log {
  exceptionRate = 100
}

(2)、registry.conf

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"

  nacos {
    application = "seata-server"
    serverAddr = "192.168.2.64:8848"
    namespace = ""
    cluster = "default"
    username = "nacos"
    password = "zhengheerp"
  }
}

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

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

4、在数据库中都加入undo_log表

每个参与分布式事务的数据库都要加

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 AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

5、在application.yml中加上配置

tx-service-group值:与第2步设置保持一致。每个参与分布式事务的服务都要加

spring:
  cloud:
    alibaba:
      seata:
        tx-service-group: tx_group

6、使用

在入口方法上加 @GlobalTransactional 注解,开启事务

7、注意

使用openfeign服务调用时,要在feign实现层加上@Service注解,
还报错的话configration配置文件删除掉。

你可能感兴趣的:(原创,java)