阿里巴巴seata分布式事务终极解决方案

文章目录

  • 一、环境配置
  • 二、正文
    • 第一步:下载seata服务
    • 第二步:创建Seata高可用的db,以及AT模式所需的undo_log表
    • 第三步:加入seata依赖:
    • 第四步:加入seata所需的参数配置:
    • 第五步:配置为高可用db模式参数并提交至配置中心:
    • 第六步:更改服务端的注册&配置中心为nacos:
    • 第七步:加入全局事务注解并启动Seata-server进行调试:
    • 第八步:高可用Seata-server搭建
  • 三、启动
  • 四、常见问题

关于seata就不做过多介绍了,网上一大片,请自行翻阅

一、环境配置

  • mysql: 5.7
  • nacos: 1.4.1
  • spring-cloud-alibaba: 2.2.1
  • seata: 1.2.0

二、正文

第一步:下载seata服务

第二步:创建Seata高可用的db,以及AT模式所需的undo_log表

  1. 在你的参与全局事务的数据库中加入undo_log这张表
-- for AT mode you must to init this sql for you business database. the seata server not need it.
CREATE TABLE IF NOT EXISTS `undo_log`
(
   `id`            BIGINT(20)   NOT NULL AUTO_INCREMENT COMMENT 'increment id',
   `branch_id`     BIGINT(20)   NOT NULL COMMENT 'branch transaction id',
   `xid`           VARCHAR(100) NOT NULL COMMENT 'global transaction id',
   `context`       VARCHAR(128) NOT NULL COMMENT 'undo_log context,such as serialization',
   `rollback_info` LONGBLOB     NOT NULL COMMENT 'rollback info',
   `log_status`    INT(11)      NOT NULL COMMENT '0:normal status,1:defense status',
   `log_created`   DATETIME     NOT NULL COMMENT 'create datetime',
   `log_modified`  DATETIME     NOT NULL COMMENT 'modify datetime',
   PRIMARY KEY (`id`),
   UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = InnoDB
 AUTO_INCREMENT = 1
 DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';
  1. 在你的mysql数据库中创建名为seata的库,并使用以下下sql
-- -------------------------------- 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(96),
   `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;

第三步:加入seata依赖:

springcloud:

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

第四步:加入seata所需的参数配置:

从官方github仓库拿到参考配置做修改:https://github.com/seata/seata/tree/develop/script/client
加到你项目的application.yml中.

seata:
enabled: true
application-id: applicationName
tx-service-group: my_test_tx_group
enable-auto-data-source-proxy: true
config:
  type: nacos
  nacos:
    namespace:
    serverAddr: 127.0.0.1:8848
    group: SEATA_GROUP
    userName: "nacos"
    password: "nacos"
registry:
  type: nacos
  nacos:
    application: seata-server
    server-addr: 127.0.0.1:8848
    namespace:
    userName: "nacos"
    password: "nacos"

第五步:配置为高可用db模式参数并提交至配置中心:

运行你下载的nacos,并参考https://github.com/seata/seata/tree/develop/script/config-center 的config.txt并修改
mysql8注意driverClassName改成com.mysql.cj.jdbc.Driver,url必须添加serverTimeZone
或者直接创建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
store.db.user=username
store.db.password=password
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

运行仓库中提供的nacos脚本,将以上信息提交到nacos控制台,如果有需要更改,可直接通过控制台更改
这里贴出来也可以直接使用
创建nacos-config.sh文件:

#!/usr/bin/env bash
# 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

urlencode() {
  for ((i=0; i < ${#1}; i++))
  do
    char="${1:$i:1}"
    case $char in
    [a-zA-Z0-9.~_-]) printf $char ;;
    *) printf '%%%02X' "'$char" ;;
    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"

failCount=0
tempLog=$(mktemp -u)
function addConfig() {
  curl -X POST -H "${contentType}" "http://$nacosAddr/nacos/v1/cs/configs?dataId=$(urlencode $1)&group=$group&content=$(urlencode $2)&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++ ))
  fi
}

count=0
for line in $(cat $(dirname "$PWD")/config.txt | sed s/[[:space:]]//g); do
  (( count++ ))
	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

本地推送nacos
,t:命名空间,g:分组,-p 端口,-h nacos配置中心地址

sh nacos-config.sh -h 127.0.0.1 -p 8848 -t 5e22d16b-da6c-4f3f-8f3a-41cb501f18e5 -g SEATA_GROUP

config.txt文件必须在cacos-config.sh上一级目录

第六步:更改服务端的注册&配置中心为nacos:

更改server中的registry.conf

registry {
 # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
 type = "nacos"
 nacos {
   application = "seata-server"
   serverAddr = "localhost"
   namespace = ""
   cluster = "default"
   username = "nacos"
   password = "nacos"
}
}

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

 nacos {
   serverAddr = "localhost"
   namespace = ""
   group = "SEATA_GROUP"
   username = "nacos"
   password = "nacos"
}
}

第七步:加入全局事务注解并启动Seata-server进行调试:

运行seata-server.sh -h ip -p 端口,成功后,运行自己的服务提供者,服务参与者.不指定时获取当前的 IP,外部访问部署在云环境和容器中的 server 建议指定
参数 全写 作用 备注
-h --host 指定在注册中心注册的 IP 不指定时获取当前的 IP,外部访问部署在云环境和容器中的 server 建议指定
-p --port 指定 server 启动的端口 默认为 8091
-m --storeMode 事务日志存储方式 支持file,db,redis,默认为 file 注:redis需seata-server 1.3版本及以上
-n --serverNode 用于指定seata-server节点ID 如 1,2,3…, 默认为 1
-e --seataEnv 指定 seata-server 运行环境 如 dev, test 等, 服务启动时会使用 registry-dev.conf 这样的配置

如:

$ sh ./bin/seata-server.sh -p 8091 -h 127.0.0.1 -m file

在全局事务调用者(发起全局事务的服务)的接口上加入@GlobalTransactional
进行测试即可.

第八步:高可用Seata-server搭建

确保你已经完成了以上七步操作后,按照以上的第1,6两步即可把你的seata新节点接入到同一个nacos集群,配置&注册中心中,由于是同一个配置中心,所以db也是采用的共同配置.至此高可用搭建已经顺利完结,如果你想测试,仅需关掉其中一个server节点,验证服务是否可用即可.

三、启动

添加守护进程

vim /lib/systemd/system/seata-server.service

文件中填入

[Unit]
Description=seata-server
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=simple
ExecStart=/opt/seata/bin/seata-server.sh -h xx.xx.xx.xx -p xx -m db
Restart=always
PrivateTmp=true

[Install]
WantedBy=multi-user.target

赋予权限

chmod 777 /opt/seata/bin/seata-server.sh
chmod 777 /lib/systemd/system/seata-server.service

启动

systemctl enable seata-server.service
systemctl daemon-reload

运行

systemctl start seata-server.service

查看状态

systemctl status seata-server.service

查看进程

ps -ef|grep seata-server

查看日志
sudo journalctl -u seata-server
如果发现日志打印
阿里巴巴seata分布式事务终极解决方案_第1张图片
解决方法:
查看java安装位置

[root@iz8vb2mwgttf5068nlwmp7z seata]# which java
/usr/local/java/jdk1.8.0_141/bin/java

建立软连接

ln -s /usr/local/java/jdk1.8.0_141/bin/java /usr/bin/java

设置开机启动


四、常见问题

  1. 事务分组配置出错导致无法找到tc
    般由于对事务分组的理解出现偏差导致的,请仔细阅读官网的参数配置中的介绍.

TM端: seata.tx-service-group=自定分组名 seata.service.vgroup-mapping(配置中心中是叫:service.vgroupMapping).自定分组名=服务端注册中心配置的cluster/application的值

拿nacos举例子

比如我server中nacos的cluster

nacos {
  application = "seata-server"
  serverAddr = "localhost"
  namespace = ""
  cluster = "testCluster"
  username = "nacos"
  password = "nacos"
}

我的事务分组为

seata:
tx-service-group: test

那么nacos中需要配置test事务分组

service.vgroupMapping.test=testCluster
  1. 使用 AT 模式需要的注意事项有哪些 ?
  • 必须使用代理数据源,有 3 种形式可以代理数据源:
  • 依赖 seata-spring-boot-starter 时,自动代理数据源,无需额外处理。
  • 依赖 seata-all 时,使用 @EnableAutoDataSourceProxy (since 1.1.0) 注解,注解参数可选择 jdk 代理或者 cglib 代理。
  • 依赖 seata-all 时,也可以手动使用 DatasourceProxy 来包装 DataSource。
  • 配置 GlobalTransactionScanner,使用 seata-all 时需要手动配置,使用 seata-spring-boot-starter 时无需额外处理。
  • 业务表中必须包含单列主键,若存在复合主键,请参考问题 13 。
  • 每个业务库中必须包含 undo_log 表,若与分库分表组件联用,分库不分表。
  • 跨微服务链路的事务需要对相应 RPC 框架支持,目前 seata-all 中已经支持:Apache Dubbo、Alibaba Dubbo、sofa-RPC、Motan、gRpc、httpClient,对于 Spring Cloud 的支持,请大家引用 spring-cloud-alibaba-seata。其他自研框架、异步模型、消息消费事务模型请结合 API 自行支持。
  • 目前AT模式支持的数据库有:MySQL、Oracle、PostgreSQL和 TiDB。
  • 使用注解开启分布式事务时,若默认服务 provider 端加入 consumer 端的事务,provider 可不标注注解。但是,provider 同样需要相应的依赖和配置,仅可省略注解。
  • 使用注解开启分布式事务时,若要求事务回滚,必须将异常抛出到事务的发起方,被事务发起方的 @GlobalTransactional 注解感知到。provide 直接抛出异常 或 定义错误码由 consumer 判断再抛出异常。
  1. 服务熔断或者参与方做了全局异常捕获后,事务回滚的几种方式介绍与示例

方式一:

通过result code 来做手动api回滚

方式二:

通过result code 抛出异常触发回滚

方式三:

服务熔断实现内直接抛出异常

方式四:

服务熔断内api触发回滚

欢迎更多方式补充…

  1. 如何使用保证捕获异常后还可以回滚事务

方式一:

使用api方式回滚事务

方式二:

全局异常捕获器位于全局事务的外层

  1. 分布式事务带来的性能降低,优化方式.

异步化当前全局事务整体调用链,缓存对应的事务状态

前端通过轮询来得到结果

请稍后…

10s 倒计时

已完成

你可能感兴趣的:(seata,java,spring,spring,boot,分布式)