seata


seata怎么实现事务一致性的
在这里插入图片描述
seata有个服务端,A服务事务成功,B服务失败,数据库有个undog,存储了A的操作,有个id,如果B失败了,seata就会去根据这个id删除A刚才的操作

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

seata事务管理中的三个角色

TC(Transaction Coordinator)-事务协调者:维护全局和分支事务的状态,协调全局事务提交或回滚。
TM(Transaction Manager)-事务管理器:定义全局事务的范围、开始全局事务、提交或回滚全局事务。
RM(Resource Manager)~资源管理器:管理分支事务处理的资源,与TC交谈以注册分支事务和报告分支事务的状
态,并驱动分支事务提交或回滚。
在这里插入图片描述

seata安装和部署

  • 安装
    下载地址:https://github.com/apache/incubator-seata
    下载后解压到本地,
  • 编辑配置文件application.yml
    在这里插入图片描述
  • 配置文件内容
    seata 1.*的版本配置文件是在seata文件夹 - conf文件夹 - registry.conf
    seata 2.*的版本配置文件是在seata文件夹 - conf文件夹 - application.yml

我用的是2.0.0,编辑application.yml,修改了三部分内容:seata.configseata.registryseata.store,前两个都是注册中心的信息,store是数据库的信息

#  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.

server:
  port: 7091

spring:
  application:
    name: seata-server

logging:
  config: classpath:logback-spring.xml
  file:
    path: ${log.home:${user.home}/logs/seata}
  extend:
    logstash-appender:
      destination: 127.0.0.1:4560
    kafka-appender:
      bootstrap-servers: 127.0.0.1:9092
      topic: logback_to_logstash

console:
  user:
    username: seata
    password: seata
seata:
  config:
    # support: nacos, consul, apollo, zk, etcd3
    type: nacos
    nacos:
      server-addr: 127.0.0.1:8848
      namespace:
      group: SEATA_GROUP
      # username: nacos
      # password: nacos
      context-path:
      ##if use MSE Nacos with auth, mutex with username/password attribute
      #access-key:
      #secret-key:
      data-id: seataServer.properties    
  registry:
    # support: nacos, eureka, redis, zk, consul, etcd3, sofa
    type: nacos
    nacos:
      application: seata-server
      server-addr: 127.0.0.1:8848
      group: SEATA_GROUP
      namespace:
      cluster: default
      # username: nacos
      # password: nacos
      context-path:
      ##if use MSE Nacos with auth, mutex with username/password attribute
      #access-key:
      #secret-key:
  store:
    # support: file 、 db 、 redis 、 raft
    mode: db
    db:
      datasource: druid
      db-type: mysql
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/aaa?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
      user: root
      password: root
      min-conn: 10
      max-conn: 100
      global-table: global_table
      branch-table: branch_table
      lock-table: lock_table
      distributed-lock-table: distributed_lock
      query-limit: 1000
      max-wait: 5000
  #  server:
  #    service-port: 8091 #If not configured, the default is '${server.port} + 1000'
  #  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,/**/*.jpeg,/**/*.ico,/api/v1/auth/login,/metadata/v1/**

  • 启动seata,启动bin目录下的文件
    window启动seata-server.bat
    linux启动seata-server.sh
    在这里插入图片描述
  • 看下注册到nacos没有,我的已经成功注册
    在这里插入图片描述
  • 看下seata控制台能访问吗,http://localhost:7091/,密码默认都是seata
    在这里插入图片描述
    到此,seata就安装部署好了,接下来就是集成到java代码中。

集成到java项目

创建seata需要的表,用来回滚

表名作用
global_table存储全局事务的相关信息,包括全局事务ID、状态、参与者等。
branch_table存储分支事务的相关信息,包括分支事务ID、关联的全局事务ID、资源信息等。
lock_table存储锁定资源的信息,用于防止并发修改。
undo_log存储撤销日志,用于在事务回滚时恢复数据。
  • 如果有单独的seata库,以下三张表放在seata库中,如果没有,可以放在业务库
 -- -------------------------------- 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,
    `gmt_modified`      DATETIME,
    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;

  • undo_log
    如果每一个微服务都想参与到全局事务中,则每个微服务都需要创建一个回滚日志表 UNDO_LOG。
-- 注意此处0.3.0+ 增加唯一索引 ux_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;

seata四种模式

遇到问题

xid为null或者不一致

RootContext.getXID()查看xid的值,或者在控制台或者在日志中也有
在这里插入图片描述
查看调用方和被调用方的xid是否一致,如果不一致,就是xid没有带过去,如果使用的是restTemplate,就手动给头里面塞进去

undo_log里面没有信息

在事务结束之前debug,然后再查看undo_log表有没有值,如果结束debug之前也没有,那就是xid的问题,确认下xid是否一致

事务没有生效,没有回滚

看看控制台有没有报错,如果没有报错,事务也没生效,就确认undo_log会不会有数据

no available service found in cluster ‘seata-server’

  • 错误信息:
    在这里插入图片描述
  • 解决
    springboot配置的cluster要跟seata中配置的一样,不然就一直报no available service found in cluster 'seata-server'
    在这里插入图片描述

service.vgroupMapping.seata-demo configuration item is required

  • 错误信息
    在这里插入图片描述
  • 解决
    如图,要对应上,seata-server是seata服务端的ip和端口,也要对得上,不然就会一直报service.vgroupMapping.seata-demo configuration item is required
    在这里插入图片描述
    还有一个data-id和nacos配置文件的对应
    在这里插入图片描述

如果还是报service.vgroupMapping.seata-demo configuration item is required,改一下tx-service-group的值,然后清理缓存,重启idea,多次尝试,可能哪里有缓存

io.seata.rm.datasource.exec.AbstractDMLBaseExecutor [146] -| execute executeAutoCommitTrue error:io.seata.core.exception.RmTransactionException: Response[ TransactionException[Could not found global transaction xid = 10.*****:8091:7404225675246635483, may be has finished.] ]

一个很奇怪的现象,报错信息可能会有差异,大概信息就是分支事务异常。
找了很多网上的信息,可能报错是一样的,但是场景不一样,我这次遇到的是。
一个简单的修改语句,其它的数据都是正常执行的,只有这条数据有这个问题
这条数据,没什么特别的,加了@GlobalTransactional就会报错,不加就正常执行。数据库能正常修改,但是修改的时候就会报分支事务失败,研究很久也没解决。
在本地部署了一套seata,这条数据正常执行,seata配置文件原版的基础上配置了nacos和db,这条数据也一切正常。
切回开发环境(seata是在服务器),就又出现这个问题,
查看seata的log,发现是这个数据id在seata产生死锁了,重启seata正常了

日志文件

linux启动seata的时候,提示seata-server is starting, you can check the /root/logs/seata/ *.log
如果这个目录不存在,需要手动创建,否则没有日志

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值