Seata

https://seata.apache.org/zh-cn/

Seata架构?

  • TC(Transaction Coordinator),事务协调者:维护全局和分支事务的状态,协调全局事务提交或回滚。

  • TM(Transaction Manager)事务管理器:定义全局事务的范围、开始全局事务、提交或回滚全局事务。

  • RM(Resource Manager)资源管理器:管理分支事务处理的资源,与TC交谈以注册分支事务和报告分支事务的状态,并驱动分支事务提交或回滚。

Seata提供哪儿四种分布式事务解决方案?

名称一致性业务侵入

XA模式

强一致性

AT模式(默认模式)

最终一致性

TCC模式

最终一致性

长事务模式

最终一致性

如何部署TC(事务协调者)服务?

docker-compose配置,请参考:https://github.com/yangsx95/notes-projects/tree/master/notes-seata

下载seata:https://seata.apache.org/zh-cn/unversioned/download/seata-server

高版本Seata需要配置配置文件application.yml

server:  
  port: 7091  
  
spring:  
  application:  
    name: seata-server  
  
logging:  
  config: classpath:logback-spring.xml  
  file:  
    path: /logs/seata  
#  extend:  
#    logstash-appender:  
#      destination: 127.0.0.1:4560  
#    kafka-appender:  
#      bootstrap-servers: 127.0.0.1:9092  
#      topic: logback_to_logstash  
  
# seata控制台的用户名密码  
console:  
  user:  
    username: seata  
    password: seata  
  
seata:  
  config:  
    # support: nacos, consul, apollo, zk, etcd3  
    type: nacos  
    nacos:  
      server-addr: nacos-server:8848  
      namespace: public  
      group: DEFAULT_GROUP  
      username: nacos  
      password: nacos  
      data-id: seataServer.properties  
  
  registry:  
    # support: nacos, eureka, redis, zk, consul, etcd3, sofa  
    type: nacos  
    nacos:  
      application: seata-server  
      server-addr: nacos-server:8848  
      group: DEFAULT_GROUP  
      namespace: public  
      # tc集群名称  
      cluster: default  
      username: nacos  
      password: nacos  
    server:  
      service-port: 8091 #If not configured, the default is '${server.port} + 1000'  
  security:  
    secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017  
    tokenValidityInMilliseconds: 1800000  
    ignore:  
      urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login

在naocs中增加配置:

配置文件内容:

store.mode=db  
#-----db-----  
store.db.datasource=druid  
store.db.dbType=mysql  
# 需要根据mysql的版本调整driverClassName  
# mysql8及以上版本对应的driver:com.mysql.cj.jdbc.Driver  
# mysql8以下版本的driver:com.mysql.jdbc.Driver  
store.db.driverClassName=com.mysql.cj.jdbc.Driver  
store.db.url=jdbc:mysql://mysql:3306/seata-server?useUnicode=true&characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false  
store.db.user= root  
store.db.password=root  
# 数据库初始连接数  
store.db.minConn=1  
# 数据库最大连接数  
store.db.maxConn=20  
# 获取连接时最大等待时间 默认5000,单位毫秒  
store.db.maxWait=5000  
# 全局事务表名 默认global_table  
store.db.globalTable=global_table  
# 分支事务表名 默认branch_table  
store.db.branchTable=branch_table  
# 全局锁表名 默认lock_table  
store.db.lockTable=lock_table  
# 查询全局事务一次的最大条数 默认100  
store.db.queryLimit=100  
  
  
# undo保留天数 默认7天,log_status=1(附录3)和未正常清理的undo  
server.undo.logSaveDays=7  
# undo清理线程间隔时间 默认86400000,单位毫秒  
server.undo.logDeletePeriod=86400000  
# 二阶段提交重试超时时长 单位ms,s,m,h,d,对应毫秒,秒,分,小时,天,默认毫秒。默认值-1表示无限重试  
# 公式: timeout>=now-globalTransactionBeginTime,true表示超时则不再重试  
# 注: 达到超时时间后将不会做任何重试,有数据不一致风险,除非业务自行可校准数据,否者慎用  
server.maxCommitRetryTimeout=-1  
# 二阶段回滚重试超时时长  
server.maxRollbackRetryTimeout=-1  
# 二阶段提交未完成状态全局事务重试提交线程间隔时间 默认1000,单位毫秒  
server.recovery.committingRetryPeriod=1000  
# 二阶段异步提交状态重试提交线程间隔时间 默认1000,单位毫秒  
server.recovery.asynCommittingRetryPeriod=1000  
# 二阶段回滚状态重试回滚线程间隔时间  默认1000,单位毫秒  
server.recovery.rollbackingRetryPeriod=1000  
# 超时状态检测重试线程间隔时间 默认1000,单位毫秒,检测出超时将全局事务置入回滚会话管理器  
server.recovery.timeoutRetryPeriod=1000

创建数据库表:

-- 全局事务表  
CREATE DATABASE IF NOT EXISTS seata ;  
  
--  
-- Licensed to the Apache Software Foundation (ASF) under one or more  
-- contributor license agreements.  See the NOTICE file distributed with  
-- this work for additional information regarding copyright ownership.  
-- The ASF licenses this file to You 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.  
--  
  
-- -------------------------------- The script used when storeMode is 'db' --------------------------------  
-- the table to store GlobalSession data  
CREATE TABLE IF NOT EXISTS seata.`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_status_gmt_modified` (`status` , `gmt_modified`),  
    KEY `idx_transaction_id` (`transaction_id`)  
) ENGINE = InnoDB  
  DEFAULT CHARSET = utf8mb4;  
  
-- the table to store BranchSession data  
CREATE TABLE IF NOT EXISTS seata.`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 = utf8mb4;  
  
-- the table to store lock data  
CREATE TABLE IF NOT EXISTS seata.`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),  
    `status`         TINYINT      NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',  
    `gmt_create`     DATETIME,  
    `gmt_modified`   DATETIME,  
    PRIMARY KEY (`row_key`),  
    KEY `idx_status` (`status`),  
    KEY `idx_branch_id` (`branch_id`),  
    KEY `idx_xid` (`xid`)  
) ENGINE = InnoDB  
  DEFAULT CHARSET = utf8mb4;  
  
CREATE TABLE IF NOT EXISTS seata.`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 seata.`distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);  
INSERT INTO seata.`distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);  
INSERT INTO seata.`distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);  
INSERT INTO seata.`distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);

最后,启动seata tc服务:

sh seata-server.sh

XA事务

什么是XA事务?

其实就是二阶段提交,实在数据库的XA模式上做了简单的封装,核心RM仍然由数据库提供:

XA模式的优点是什么?

  • 事务是强一致性的,满足ACID的原则

  • 常用的数据库都支持,并且没有代码侵入

XA模式的缺点是什么?

  • 因为一阶段需要锁定资源,等待二阶段结束才释放,性能较差。

  • 一来关系型数据库才能实现。

编写XA事务使用代码

  1. 开启Seata XA模式 :seata.data-source-proxy-mode=XA

  2. 所有要分支服务服务介入到Seata tc server

  3. 在发起全局事务的入口方法添加@GlobalTransaction注解即可

@Override
@GlobalTransactional
public Long create(Order order) {
	orderMapper.insert(order);
	// 扣减库存
	// 扣减余额
	retrun order.getId();
}

AT事务

什么是AT事务?

AT模式事务的脏写问题(隔离问题)?

引入全局锁,解决两个分布式事务的隔离问题:

ABA 问题怎么解决呢??

AT模式相比XA模式的区别是什么

  • XA模式一阶段不提交事务,锁定资源;AT模式一阶段直接提交,不锁定资源。

  • XA模式一来数据库的回滚机制;AT模式利用数据快照实现数据回滚。

  • XA模式强一致性;AT模式最终一致性。

编写AT事务使用代码

  1. 在分支事务服务中,定义两张表:lock_tableundo_log,一个用于记录锁(放在TM上),一个用于记录undo-log(放在对应分值事务的RM上)。

  2. 修改所有分支事务服务的yaml配置文件,启用AT模式 seata.data-source-proxy-mode=AT

  3. 在发起全局事务的入口方法添加@GlobalTransaction注解即可。

TCC事务

什么是TCC事务?

TCC模式下,不同事物各自操作预留的资源互不影响,所以事务之间没有隔离问题,所以性能要比AT模式更高。

TCC的优点是什么?

  • 一阶段完成直接提交事务,释放数据库资源,性能好。

  • 相比AT模型,无需生成快照,无需使用全局锁,性能最强。

  • 不依赖数据库事务,而是依赖补偿操作,可以用于非事务型数据库。

  • TCC 另一个作用就是把两阶段拆分成了两个独立的阶段,通过资源业务锁定的方式进行关联。资源业务锁定方式的好处在于,既不会阻塞其他事务在第一阶段对于相同资源的继续使用,也不会影响本事务第二阶段的正确执行。

TCC的缺点是什么?

  • 代码侵入,需要人为编写Try、Confirm、Cancel,太麻烦。

  • 软状态,事务是最终一致。

  • 需要考虑Confirm和Cancel的失败情况,做好幂等处理。

TCC的空回滚和业务悬挂问题?

TCC的使用场景?

在一个项目中的 Seata 事务中,AT 模式和 TCC 模式可以并存。TCC 模式是有使用场景的,对于金额扣除和库存扣除,能够实现金额冻结和库存冻结,因此可以使用 TCC 模式。对于下单操作来说,只能进行添加或删除回滚操作,没有冻结的场景,因此只能使用 AT 模式,无法使用 TCC 模式。

也就是说,如果可以对资源进行预留,就是可以使用TCC的,反之就是不可使用的。

TCC的代码编写

  1. 多服务场景下,定义每个分支事物的 tryconfirmcancel的API接口

  2. 将分支事务的操作在主服务上包装为TccService类,并指定他们的tryconfirmcancel方法

  3. 事务入口处增加@GlobalTransaction注解,并注入所有分支事务的TccService,并调用他们的try方法,进行资源预留

TCC模式的使用心得与我遇到的应用场景

融资租赁系统与供应链系统的交互?

场景:融资租赁系统有一笔销售业务,需要销售给第三方,并且需要从供应链出库。 分布式事务问题为:销售订单交付申请通过,状态变为已出库时,需要同时通知供应链系统扣减库存。

在这个场景下,共有两个Try操作:

  1. 融资租赁系统创建销售订单,且订单状态为待出库

  2. 供应链系统创建锁定订单,状态为已锁定,锁定指定资产的出库数量,并扣减剩余库存

两个Confirm操作:

  1. 融资租赁系统更改销售订单状态为已出库

  2. 供应链系统更改锁定订单状态为已确认

两个Cancel操作:

  1. 融资租赁系统更改销售订单状态为出库失败

  2. 供应链系统更改锁定订单状态为已取消,并增加剩余库存

单个服务如何使用不同的分布式事务模式?

暂时未找到Seata如何配置同时使用XA和TA模式的方式。

一个服务同时使用XA和TA模式,违背了 Seata 的设计原则和最佳实践,容易造成事务管理的混乱和系统的不稳定,因此强烈不建议这样做。在实践中,应当将不同事务模式的需求拆分到不同的服务实例中去,每个服务实例根据其业务特点和需求选择并配置相应的事务模式(AT 或 XA)。

最后更新于