Seata分布式事务使用(seata-server安装、启动、以及AT模式使用)

在微服务中,以springcloud为例,多个微服务之间通过OpenFeign的方式调用。

现有微服务A、B两个,a为A中的事务方法,b是B中的事务方法,假设在A中有一个业务方法businessA,需要调用a,b来完成正常的业务流程处理。

调用顺序是,执行完b--->再执行a,b事务方法正常执行,b会提交事务,数据的更改也会被记录到数据库中。在执行a的时候出现异常,a事务方法由于抛出异常会正常回滚。此时业务流程是失败的,但是b的事务已经提交,无法回滚

这就是微服务中存在的事务问题

Seata可以解决这个问题官方文档地址

1.下载seata-server,1.1.0下载地址,在Assets有四个选项,这里选择seata-server-1.1.0.zip下载

2.下载之后解压,在conf目录下自定义配置。打开file.conf文件,更改mode类型为db,同时在下面的db中根据自己的数据库配置对应的账户、密码等


## transaction log store, only used in seata-server
store {
  ## store mode: file、db
  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) etc.
    datasource = "dbcp"
    ## mysql/oracle/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.jdbc.Driver"
## 如果要是没有sata数据库,要建立一个
    url = "jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&characterEncoding=UTF-8"
    user = "root"
    password = "12345"
    minConn = 1
    maxConn = 10
## 建好数据库之后新建下面的这三张表
    globalTable = "global_table"
    branchTable = "branch_table"
    lockTable = "lock_table"
    queryLimit = 100
  }
}

三张表的建表SQL地址

3.保存file.conf的配置,打开register.conf,这里的type选择springcloud的eureka,同时在下面的eureka模块中,配置eureka注册中心地址,application="seata-server"(默认是default),修改之后退出

4.进入seata-server解压之后的bin文件夹,启动seata-server,Mac下命令行启动

seata-server.sh -h 127.0.0.1 -p 9091 -m db -n 1

-h: 注册到注册中心的ip (要和注册中心的IP相同,才能注册到注册中心上去,本地就是127.0.0.1了)

-p: seata-server的端口号 

-m: 全局事务会话信息存储模式,file、db,优先读取启动参数

-n: Server node,多个Server时,需区分各自节点,用于生成不同区间的transactionId,以免冲突

5.启动之后,搭建微服务A、和B,两个微服务除了基本的配置之外,加上seata的依赖,springcloud-alibaba-seata依赖(这里面已经帮我们实现了XID在微服务之间的传递),推荐使用1.1.0版本,这个版本数据源可以不用代理,seata会自动代理,同时支持了在yml文件中配置,以前的版本都是要在每个微服务下面加file.conf和register.conf的文件,现在可以直接使用配置

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

            <!--阿里分布式事务-->
            <dependency>
                <groupId>io.seata</groupId>
                <artifactId>seata-spring-boot-starter</artifactId>
                <version>1.1.0</version>
            </dependency>

6.在两个微服务中配置,拿A服务配置举例:

server:
  port: 8084
  servlet:
    context-path: /clientTwo
  tomcat:
    connection-timeout: 5000
spring:
  main:
    allow-bean-definition-overriding: true
  application:
    name: demo-clientTwo
  datasource:
      url: jdbc:mysql://localhost:3306/dhb?useUnicode=true&characterEncoding=UTF-8
      username: root
      password: 12345
# 这里配置分组
  cloud:
    alibaba:
      seata:
        tx-service-group: my_test_tx_group
eureka:
  instance:
    instance-id: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
    lease-renewal-interval-in-seconds: 30
    lease-expiration-duration-in-seconds: 90
  client:
    service-url:
      defaultZone: http://localhost:8081/eureka/
    registry-fetch-interval-seconds: 15
# 这里配置的是微服务之间的调用超时时间
feign:
  client:
    config:
      default:
        connect-timeout: 4000
        read-timeout: 4000
#阿里分布式事务配置
seata:
  service:
    vgroup-mapping:
#这里的组名my_test_tx_group就是上面已经配置过的
# seata-server 对应的就是register.conf里的application选项的内容
      my_test_tx_group: seata-server
    grouplist:
#这里对应的就是上面的seata-server,后面的蚕食seata服务的IP地址和端口号
      seata-server: 192.168.0.105:9091
    enable-degrade: false
    disable-global-transaction: false
mybatis-plus:
  mapper-locations: classpath*:/mapper/*.xml

7.在涉及到到分布式事务的微服务对应的数据库中,都建立一张undo_log表,undo_log建表地址,undo_log是用来回滚事务的一个记录表,更多关于undo_log的说明,参考官方的AT工作机制、两阶段提交、undo_log的作用

8.在微服务A的businessA上加入@GlobalTransactional注解

9.测试,通过微服务A调用微服务B中的b事务方法,执行完毕,返回微服务A之后,手动抛出异常,看b事务是否已经回滚

@GlobalTransactional(rollbackFor = Exception.class)
    @PostMapping(value = "clientTwoSave")
    public Integer save(@RequestBody User user){

        com.example.clientone.democlientone.entity.User one = new com.example.clientone.democlientone.entity.User();
        BeanUtils.copyProperties(user,one);
        System.out.println(RootContext.getXID());
        one.setId(4432);
        testTransactionService.clientOneSaveUser(one);
        // 手动抛出异常
        int a = 1/0;
        userService.save(user);
        return user.getId();
    }

查看微服务B对应的user表并没有新增

10.在b执行完毕之后,返回微服务A,抛出异常之前debug住,查看库里的user表和undo_log表

user表

undo_log表 

可以看到,b事务正常提交之后,数据库的数据确实添加进去了,但是当异常发生之后,数据库里的数据又被复原到原来的样子了,在微服务B的控制台可以看到如下信息

控制台信息 branchId和xid都和undo_log中的数据对应。

这就是使用seata的AT模式完成的控制分布式事务的流程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章