Spring Cloud中集成 seata

记录一下seata的使用,踩坑后总结出来,作为一次记录,仅供参考!!有问题评论指出

Spring Cloud中集成 seata

step 1:安装seata服务,Window/Linux

第一步:下载安装包,解压

在官网下载需要的版本,下面提供两种方式

  • 官网的文档页面下载:http://seata.io/zh-cn/blog/download.html
  • github下载:https://github.com/seata/seata/releases

注:建议可以顺便把源码拉下来,后面可以用,github有时候访问太慢,拉下来方便用

第二步:修改文件夹 conf 中的配置

registry.conf

注意:其他的选择配置内容差不多我就只写了一种

修改属性:registry { type = "nacos" },配置我们选择的类型

作用:seata服务注册的地址

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  # 根据自己的需求选择合适的注册地址
  type = "nacos"
  ...

  nacos {
    application = "seata-server"
    # 注册中心的地址 注:不要加http
    serverAddr = "127.0.0.1:8848"
    # 分组
    group = "SEATA_GROUP"
    # 命名空间
    namespace = ""
    cluster = "default"
    # 用户名
    username = "nacos"
    # 密码
    password = "nacos"
  }
  ...
}

修改属性:config { type = "nacos" },配置我们选择的类型

作用:seata服务配置中心

config {
  # file、nacos 、apollo、zk、consul、etcd3
  # 根据自己的需求选择合适的配置中心
  # 选择file 也就是回去读取刚才我们配置的file.conf
  # 反之我们还需要单独将配置配置到相应的配置中心
  type = "nacos"

  nacos {
    # 配置中心地址
    serverAddr = "127.0.0.1:8848"
    # 命名空间
    namespace = ""
    # 分组
    group = "SEATA_GROUP"
    # 用户名
    username = ""
    # 密码
    password = ""
  }
  ...
  file {
    name = "file.conf"
  }
}

下面是完整的配置

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  # 根据自己的需求选择合适的注册地址
  type = "nacos"
  loadBalance = "RandomLoadBalance"
  loadBalanceVirtualNodes = 10

  nacos {
    application = "seata-server"
    # 注册中心的地址 注:不要加http
    serverAddr = "127.0.0.1:8848"
    # 分组
    group = "SEATA_GROUP"
    # 命名空间
    namespace = ""
    cluster = "default"
    # 用户名
    username = "nacos"
    # 密码
    password = "nacos"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = 0
    password = ""
    cluster = "default"
    timeout = 0
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  consul {
    cluster = "default"
    serverAddr = "127.0.0.1:8500"
  }
  etcd3 {
    cluster = "default"
    serverAddr = "http://localhost:2379"
  }
  sofa {
    serverAddr = "127.0.0.1:9603"
    application = "default"
    region = "DEFAULT_ZONE"
    datacenter = "DefaultDataCenter"
    cluster = "default"
    group = "SEATA_GROUP"
    addressWaitTime = "3000"
  }
  file {
    name = "file.conf"
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3
  # 根据自己的需求选择合适的配置中心
  # 选择file 也就是回去读取刚才我们配置的file.conf
  # 反之我们还需要单独将配置配置到相应的配置中心
  type = "nacos"

  nacos {
    # 配置中心地址
    serverAddr = "127.0.0.1:8848"
    # 命名空间
    namespace = ""
    # 分组
    group = "SEATA_GROUP"
    # 用户名
    username = ""
    # 密码
    password = ""
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    appId = "seata-server"
    apolloMeta = "http://192.168.1.204:8801"
    namespace = "application"
    apolloAccesskeySecret = ""
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}
file.conf

这里的配置有两种方式:

  • registry.conf中属性config{ type = "file" },则修改file.conf文件
  • registry.conf中属性config{ type = "不为file的方式" },则需要我们将配置,配置到指定的配置中心

注意:其他的选择配置内容差不多我就只写了一种的

1. type = “file”

修改属性:store { mode = "db" },配置我们选择的类型

## transaction log store, only used in seata-server
store {
  ## store mode: file、db、redis
  # 这里根据自己用户存储的类型修改 现在三种文件、数据库、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"
    # MySQL旧版驱动:com.mysql.jdbc.Driver
    # MySQL新版驱动:com.mysql.cj.jdbc.Driver
    # 根据自己的数据库库地址修改下面
    url = "jdbc:mysql://127.0.0.1:3306/seata"
    # 用户名
    user = "mysql"
    # 密码
    password = "mysql"
    ...
  }
}

下面为完整代码

## transaction log store, only used in seata-server
store {
  ## store mode: file、db、redis
  # 这里根据自己用户存储的类型修改 现在三种文件、数据库、redis
  mode = "db"

  ## file store property
  file {
    ## store location dir
    dir = "sessionStore"
    # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
    maxBranchSessionSize = 16384
    # globe session size , if exceeded throws exceptions
    maxGlobalSessionSize = 512
    # file buffer size , if exceeded allocate new buffer
    fileWriteBufferCacheSize = 16384
    # when recover batch read size
    sessionReloadReadSize = 100
    # async, sync
    flushDiskMode = async
  }

  ## 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"
    # MySQL旧版驱动:com.mysql.jdbc.Driver
    # MySQL新版驱动:com.mysql.cj.jdbc.Driver
    # 根据自己的数据库库地址修改下面
    url = "jdbc:mysql://127.0.0.1:3306/seata"
    # 用户名
    user = "mysql"
    # 密码
    password = "mysql"
    minConn = 5
    maxConn = 100
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
    maxWait = 5000
  }

  ## redis store property
  redis {
    host = "127.0.0.1"
    port = "6379"
    password = ""
    database = "0"
    minConn = 1
    maxConn = 10
    maxTotal = 100
    queryLimit = 100
  }

}
2. type = “不为file的方式”

注意:这里我们使用nacos作为配置中心

在seata的安装目录添加文件config.txt,添加以下内容

该文件可以从seata源码中 /script/config-center 中获得,源码地址
在这里插入图片描述

transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
transport.threadFactory.bossThreadPrefix=NettyBoss
transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
transport.threadFactory.shareBossWorker=false
transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
transport.threadFactory.clientSelectorThreadSize=1
transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
transport.threadFactory.bossThreadSize=1
transport.threadFactory.workerThreadSize=default
transport.shutdown.wait=3

service.vgroupMapping.my_test_tx_group=default

service.default.grouplist=10.255.74.53:8091
service.enableDegrade=false
service.disableGlobalTransaction=false

client.rm.asyncCommitBufferLimit=10000
client.rm.lock.retryInterval=10
client.rm.lock.retryTimes=30
client.rm.lock.retryPolicyBranchRollbackOnConflict=true
client.rm.reportRetryCount=5
client.rm.tableMetaCheckEnable=false
client.rm.tableMetaCheckerInterval=60000
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000

store.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://192.168.226.128:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=123456
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

server.recovery.committingRetryPeriod=1000
server.recovery.asynCommittingRetryPeriod=1000
server.recovery.rollbackingRetryPeriod=1000
server.recovery.timeoutRetryPeriod=1000
server.maxCommitRetryTimeout=-1
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false

client.undo.dataValidation=true
client.undo.logSerialization=jackson
client.undo.onlyCareUpdateColumns=true
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.undo.compress.enable=true
client.undo.compress.type=zip
client.undo.compress.threshold=64k
log.exceptionRate=100

transport.serialization=seata
transport.compressor=none

metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
client.support.spring.datasource.autoproxy=true

需要我们修改的地方

①:配置service.vgroupMapping,其中后面的my_test_tx_group是自定义的,根据自己的需求命名即可

service.vgroupMapping.my_test_tx_group=default

②:配置存储的类型,这里根据自己选择的来添加,我选择的是db方式的,所以只加入的db方式的配置

store.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://192.168.226.128:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=123456

修改完之后,我们从seata源码中copy相应的脚本到 conf 文件夹中

我这里使用的是nacos所以,进入nacos文件中

在这里插入图片描述
在这里插入图片描述

#!/bin/sh
# Copyright 1999-2019 Seata.io Group.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at、
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

while getopts ":h:p:g:t:u:w:" opt
do
  case $opt in
  h)
    host=$OPTARG
    ;;
  p)
    port=$OPTARG
    ;;
  g)
    group=$OPTARG
    ;;
  t)
    tenant=$OPTARG
    ;;
  u)
    username=$OPTARG
    ;;
  w)
    password=$OPTARG
    ;;
  ?)
    echo " USAGE OPTION: $0 [-h host] [-p port] [-g group] [-t tenant] [-u username] [-w password] "
    exit 1
    ;;
  esac
done

if [ -z ${host} ]; then
    host=localhost
fi
if [ -z ${port} ]; then
    port=8848
fi
if [ -z ${group} ]; then
    group="SEATA_GROUP"
fi
if [ -z ${tenant} ]; then
    tenant=""
fi
if [ -z ${username} ]; then
    username=""
fi
if [ -z ${password} ]; then
    password=""
fi

nacosAddr=$host:$port
contentType="content-type:application/json;charset=UTF-8"

echo "set nacosAddr=$nacosAddr"
echo "set group=$group"

urlencode() {
  length="${#1}"
  i=0
  while [ $length -gt $i ]; do
    char="${1:$i:1}"
    case $char in
    [a-zA-Z0-9.~_-]) printf $char ;;
    *) printf '%%%02X' "'$char" ;;
    esac
    i=`expr $i + 1`
  done
}

failCount=0
tempLog=$(mktemp -u)
function addConfig() {
  dataId=`urlencode $1`
  content=`urlencode $2`
  curl -X POST -H "${contentType}" "http://$nacosAddr/nacos/v1/cs/configs?dataId=$dataId&group=$group&content=$content&tenant=$tenant&username=$username&password=$password" >"${tempLog}" 2>/dev/null
  if [ -z $(cat "${tempLog}") ]; then
    echo " Please check the cluster status. "
    exit 1
  fi
  if [ "$(cat "${tempLog}")" == "true" ]; then
    echo "Set $1=$2 successfully "
  else
    echo "Set $1=$2 failure "
    failCount=`expr $failCount + 1`
  fi
}

count=0
for line in $(cat $(dirname "$PWD")/config.txt | sed s/[[:space:]]//g); do
    count=`expr $count + 1`
	key=${line%%=*}
    value=${line#*=}
	addConfig "${key}" "${value}"
done

echo "========================================================================="
echo " Complete initialization parameters,  total-count:$count ,  failure-count:$failCount "
echo "========================================================================="

if [ ${failCount} -eq 0 ]; then
	echo " Init nacos config finished, please start seata-server. "
else
	echo " init nacos config fail. "
fi

执行脚本,将配置文件配置到配置中心

注意:执行脚本要使用cmd的方式启动,或者使用git的bash的方式,直接点击脚本会闪退

参数说明:

-h: host,默认值 localhost

-p: port,默认值 8848

-g: 配置分组,默认值为 ‘SEATA_GROUP’

-t: 租户信息,对应 Nacos 的命名空间ID字段, 默认值为空 ‘’

window下执行,找到脚本存放的位置,点开cmd

nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -t 5a3c7d6c-f497-4d68-a71a-2e5e3340b3ca

Linux下执行

sh /路径/nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -t 5a3c7d6c-f497-4d68-a71a-2e5e3340b3ca

执行脚本后会弹出一个bash弹框,每个配置项是否成功后面会显示 successful

注:上面命令可以在官方文档中找到,具体情况可以去了解

第三步:导入表

该文件可以通过源码获得,下面提供MySQL

-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `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`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
    `branch_id`         BIGINT       NOT NULL,
    `xid`               VARCHAR(128) NOT NULL,
    `transaction_id`    BIGINT,
    `resource_group_id` VARCHAR(32),
    `resource_id`       VARCHAR(256),
    `branch_type`       VARCHAR(8),
    `status`            TINYINT,
    `client_id`         VARCHAR(64),
    `application_data`  VARCHAR(2000),
    `gmt_create`        DATETIME(6),
    `gmt_modified`      DATETIME(6),
    PRIMARY KEY (`branch_id`),
    KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
    `row_key`        VARCHAR(128) NOT NULL,
    `xid`            VARCHAR(128),
    `transaction_id` BIGINT,
    `branch_id`      BIGINT       NOT NULL,
    `resource_id`    VARCHAR(256),
    `table_name`     VARCHAR(32),
    `pk`             VARCHAR(36),
    `gmt_create`     DATETIME,
    `gmt_modified`   DATETIME,
    PRIMARY KEY (`row_key`),
    KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8;

CREATE TABLE IF NOT EXISTS `distributed_lock`
(
    `lock_key`       CHAR(20) NOT NULL,
    `lock_value`     VARCHAR(20) NOT NULL,
    `expire`         BIGINT,
    primary key (`lock_key`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);

最后启动到bin目录中启动 seata 服务

注:以上大部分都可以从seata官方文档找到,不确定的可以去官网找找

官网文档地址

step 2:集成 seata 客户端

第一步:导包

这里引用官方推荐,具体位置官方文档 – 部署 – 新人文档

这里也附上github上面的文档地址:https://github.com/seata/seata-samples/blob/master/doc/quick-integration-with-spring-cloud.md

<dependency>
    <groupId>io.seata</groupId>
    <artifactId>seata-spring-boot-starter</artifactId>
    <version>最新版</version>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
    <version>2.2.1.RELEASE</version>
    <exclusions>
        <exclusion>
            <groupId>io.seata</groupId>
            <artifactId>seata-spring-boot-starter</artifactId>
        </exclusion>
    </exclusions>
</dependency>

第二步:配置 seata 属性

这里有两种方式:

1️⃣(推荐):在application.yml中添加seata

seata:
  enabled: true
  application-id: ${spring.application.name}
  tx-service-group: my_test_tx_group # 这里根据自己服务端中配置的来写
  enable-auto-data-source-proxy: false
  service:
    vgroupMapping:
      seata-account-group: default
    disable-global-transaction: false

  registry:
    type: nacos # 注册中心方式
    nacos:
      application: "seata-server"
      serverAddr: "127.0.0.1:8848" # 注册中心地址
      group: "SEATA_GROUP" # 注册中心分组
      namespace: "SEATA_GROUP" # 命名空间ID
      username: "nacos"
      password: "nacos"
  config:
    type: nacos # 配置中心方式
    nacos:
      serverAddr: "192.168.226.128:8848"
      namespace: "SEATA_GROUP"
      group: "SEATA_GROUP"
      username: "nacos"
      password: "nacos"

2️⃣:同样也是修改 application.yml 但是是配置在spring下面的

spring:
  application:
    name: server-user-8005
  cloud:
    alibaba:
      seata:
        tx-service-group: my_test_tx_group

最开始就一直用这个,但是无论如何都要报错,各种奇怪的问题,之后就换了

第三步:在业务相关的数据库添加表

1️⃣:如果使用的是 AT 模式,导入 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

2️⃣:如果使用的是 TCC 模式,导入 tcc_fence_log ,也可以在,源码地址找到

CREATE TABLE IF NOT EXISTS `tcc_fence_log`
(
    `xid`           VARCHAR(128)  NOT NULL COMMENT 'global id',
    `branch_id`     BIGINT        NOT NULL COMMENT 'branch id',
    `action_name`   VARCHAR(64)   NOT NULL COMMENT 'action name',
    `status`        TINYINT       NOT NULL COMMENT 'status(tried:1;committed:2;rollbacked:3;suspended:4)',
    `gmt_create`    DATETIME(3)   NOT NULL COMMENT 'create time',
    `gmt_modified`  DATETIME(3)   NOT NULL COMMENT 'update time',
    PRIMARY KEY (`xid`, `branch_id`),
    KEY `idx_gmt_modified` (`gmt_modified`),
    KEY `idx_status` (`status`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;

第四步:需要的业务方法上添加注解

@GlobalTransactional(name = "my_test_tx_group",rollbackFor = Exception.class)

运行,一个简单的demo就可以跑了

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值