SpringCloud Alibaba Seata处理分布式事务

目录

一、概述

1、简介

2、分布式事务处理过程的一ID+三组件模型

3、一个典型的分布式事务过程

 4、下载地址

5、怎么玩

 二、Seata-Server安装

1、下载版本

2、修改file.conf配置文件

3、数据库新建库seata

4、在seata库里建表

5、修改seata-server-1.0.0\seata\conf目录下的registry.conf配置文件

6、启动

三、测试环境搭建之订单/库存/账户业务数据库准备

1、建库

2、建表

3、最终效果

 四、测试环境搭建之seata-order-service2001

1、建模块

2、pom

3、yml

4、主启动

6、dao

7、service(feign)

8、controller

9、conf

10、file.conf和registry.conf

11、最终效果

 五、测试环境搭建之Storage-Module2002

1、domin

2、dao

3、service

4、controller(order中的feign配置要一致)

5、最终效果

 六、测试环境搭建之Account-Module2003

1、domin

2、dao

3、service

4、controller(与order中的feign配置匹配)

5、最终效果

 七、测试

1、正常下单

 2、超时异常,没加@GlobalTransactional

3、超时异常,加@GlobalTransactional

八、seata的运行机制

1、再看TC/TM/RM三大组件

2、AT模式如何做到对业务的无侵入


分布式事务问题

单机单库没这个问题,用本地的事务管理就行,

单体应用被拆分成微服务应用,原来的三个模块被拆分成三个独立的应用,分别使用三个独立的数据源,
业务操作需要调用三个服务来完成。此时每个服务内部的数据一致性由本地事务来保证,但是全局的数据一致性问题没法保证。

SpringCloud Alibaba Seata处理分布式事务_第1张图片

总结:一次业务操作需要跨多个数据源或需要跨多个系统进行远程调用,就会产生分布式事务问题

一、概述

1、简介

Seata是一款开源的分布式事务解决方案,致力于在微服务架构下提供高性能和简单易用的分布式事务服务。

官方文档

Seatahttp://seata.io/zh-cn/

2、分布式事务处理过程的一ID+三组件模型

Transaction ID XID:全局唯一的事务ID

Transaction Coordinator (TC)

事务协调器,维护全局事务的运行状态,负责协调并驱动全局事务的提交或回滚;

Transaction Manager (TM)

控制全局事务的边界,负责开启一个全局事务,并最终发起全局提交或全局回滚的决议;

Resource Manager (RM)

控制分支事务,负责分支注册、状态汇报,并接收事务协调器的指令,驱动分支(本地)事务的提交和回滚

3、一个典型的分布式事务过程

TM 向 TC 申请开启一个全局事务,全局事务创建成功并生成一个全局唯一的 XID;
XID 在微服务调用链路的上下文中传播;
RM 向 TC 注册分支事务,将其纳入 XID 对应全局事务的管辖;
TM 向 TC 发起针对 XID 的全局提交或回滚决议;
TC 调度 XID 下管辖的全部分支事务完成提交或回滚请求。

 SpringCloud Alibaba Seata处理分布式事务_第2张图片

 4、下载地址

Releases · seata/seata · GitHubhttps://github.com/seata/seata/releases

5、怎么玩

跟本地的事务管理一样只要一个注解就能搞定

本地@Transactional

全局@GlobalTransactional

SpringCloud Alibaba Seata处理分布式事务_第3张图片

 二、Seata-Server安装

1、下载版本

我下载的是1.0.0版本的

地址

Releases · seata/seata · GitHubhttps://github.com/seata/seata/releases

2、修改file.conf配置文件

seata-server-0.9.0.zip解压到指定目录并
修改conf目录下的file.conf配置文件

记得先备份

主要修改:自定义事务组名称+事务日志存储模式为db+数据库连接信息

service模块的修改

service {
  #transaction service group mapping
  vgroup_mapping.my_test_tx_group = "xiaojiang_tx_group"
  #only support when registry.type=file, please don't set multiple addresses
  default.grouplist = "127.0.0.1:8091"
  #disable seata
  disableGlobalTransaction = false
}

store模块的修改

store {
  ## store mode: file、db
  mode = "db"

  ## file store property
  file {
    ## store location dir
    dir = "sessionStore"
  }

  ## database store property
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
    datasource = "dbcp"
    ## mysql/oracle/h2/oceanbase etc.
    db-type = "mysql"
    driver-class-name = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://localhost:3306/seata"
    user = "root"
    password = "123456"

  }
}

3、数据库新建库seata

在这里由于我的mysql的版本是8.0.*的,而seata的lib目录下的mysql驱动包是5.0.*版本的,所以得替换,否则连不上数据库

 新建库seata

4、在seata库里建表

由于在seata1.0.0之后在安装包不再提供建表sql文件,所以需要去官方文档拷贝

https://github.com/seata/seata/blob/develop/script/server/db/mysql.sql

 
-- the table to store GlobalSession data
drop table if exists `global_table`;
create table `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`)
);
 
-- the table to store BranchSession data
drop table if exists `branch_table`;
create table `branch_table` (
  `branch_id` bigint not null,
  `xid` varchar(128) not null,
  `transaction_id` bigint ,
  `resource_group_id` varchar(32),
  `resource_id` varchar(256) ,
  `lock_key` varchar(128) ,
  `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`)
);
 
-- the table to store lock data
drop table if exists `lock_table`;
create table `lock_table` (
  `row_key` varchar(128) not null,
  `xid` varchar(96),
  `transaction_id` long ,
  `branch_id` long,
  `resource_id` varchar(256) ,
  `table_name` varchar(32) ,
  `pk` varchar(36) ,
  `gmt_create` datetime ,
  `gmt_modified` datetime,
  primary key(`row_key`)
);

5、修改seata-server-1.0.0\seata\conf目录下的registry.conf配置文件

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"
 
  nacos {
    serverAddr = "localhost:8848"
    namespace = ""
    cluster = "default"
  }

目的是:指明注册中心为nacos,及修改nacos连接信息

6、启动

先启动nacos

在seata-server-1.0.0\seata\bin打开cmd

用seata-server.bat -p 8091来启动,也可直接打开seata-server.bat文件

SpringCloud Alibaba Seata处理分布式事务_第4张图片

三、测试环境搭建之订单/库存/账户业务数据库准备

 
这里我们会创建三个服务,一个订单服务,一个库存服务,一个账户服务。
 
当用户下单时,会在订单服务中创建一个订单,然后通过远程调用库存服务来扣减下单商品的库存,
再通过远程调用账户服务来扣减用户账户里面的余额,
最后在订单服务中修改订单状态为已完成。
 
该操作跨越三个数据库,有两次远程调用,很明显会有分布式事务问题。
需要启动nacos和seata

1、建库

seata_order:存储订单的数据库;

seata_storage:存储库存的数据库;

seata_account:存储账户信息的数据库。

建库sql

 
CREATE DATABASE seata_order;
 
CREATE DATABASE seata_storage;
 
CREATE DATABASE seata_account;

2、建表

由于SEATA AT 模式需要 UNDO_LOG 表,所以除了建普通的表,还需建UNDO_LOG

UNDO_LOG需在官方文档拷贝,每个数据库都得建

https://github.com/seata/seata/blob/develop/script/client/at/db/mysql.sql

CREATE TABLE IF NOT EXISTS `undo_log`
(
    `branch_id`     BIGINT       NOT NULL COMMENT 'branch transaction id',
    `xid`           VARCHAR(128) 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(6)  NOT NULL COMMENT 'create datetime',
    `log_modified`  DATETIME(6)  NOT NULL COMMENT 'modify datetime',
    UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = InnoDB
  AUTO_INCREMENT = 1
  DEFAULT CHARSET = utf8mb4 COMMENT ='AT transaction mode undo table';

建业务表

seata_order库下建t_order表

 
CREATE TABLE t_order (
  `id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `user_id` BIGINT(11) DEFAULT NULL COMMENT '用户id',
  `product_id` BIGINT(11) DEFAULT NULL COMMENT '产品id',
  `count` INT(11) DEFAULT NULL COMMENT '数量',
  `money` DECIMAL(11,0) DEFAULT NULL COMMENT '金额',
  `status` INT(1) DEFAULT NULL COMMENT '订单状态:0:创建中;1:已完结'
) ENGINE=INNODB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
 
SELECT * FROM t_order;

seata_storage库下建t_storage 表

 
CREATE TABLE t_storage (
 `id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
 `product_id` BIGINT(11) DEFAULT NULL COMMENT '产品id',
 `total` INT(11) DEFAULT NULL COMMENT '总库存',
 `used` INT(11) DEFAULT NULL COMMENT '已用库存',
 `residue` INT(11) DEFAULT NULL COMMENT '剩余库存'
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
 
 
INSERT INTO seata_storage.t_storage(`id`, `product_id`, `total`, `used`, `residue`)
VALUES ('1', '1', '100', '0', '100');
 
SELECT * FROM t_storage;

seata_account库下建t_account 表

 
CREATE TABLE t_account (
  `id` BIGINT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'id',
  `user_id` BIGINT(11) DEFAULT NULL COMMENT '用户id',
  `total` DECIMAL(10,0) DEFAULT NULL COMMENT '总额度',
  `used` DECIMAL(10,0) DEFAULT NULL COMMENT '已用余额',
  `residue` DECIMAL(10,0) DEFAULT '0' COMMENT '剩余可用额度'
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
 
INSERT INTO seata_account.t_account(`id`, `user_id`, `total`, `used`, `residue`)  VALUES ('1', '1', '1000', '0', '1000');
 
SELECT * FROM t_account;

3、最终效果

SpringCloud Alibaba Seata处理分布式事务_第5张图片

 四、测试环境搭建之seata-order-service2001

1、建模块

建立seata-order-service2001模块

2、pom

我alibaba的版本选择的是2.1.2



    com.alibaba.cloud
    spring-cloud-starter-alibaba-nacos-discovery

        com.alibaba.cloud
        spring-cloud-starter-alibaba-seata
        
            
                io.seata
                seata-spring-boot-starter
            
        
    
    
        io.seata
        seata-spring-boot-starter
        1.0.0
    
    
    
        org.springframework.cloud
        spring-cloud-starter-openfeign
    
    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
        org.springframework.boot
        spring-boot-starter-actuator
    
    
    
        mysql
        mysql-connector-java
        8.0.28
    
    
        com.alibaba
        druid-spring-boot-starter
        1.1.10
    
    
        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        2.0.0
    
    
        org.springframework.boot
        spring-boot-starter-test
        test
    
    
        org.projectlombok
        lombok
        true
    

3、yml

server:
  port: 2001

spring:
  application:
    name: seata-order-service
  main:
/
    allow-bean-definition-overriding: true
  cloud:
    nacos:
      server-addr: localhost:8848
    alibaba:
      seata:
        tx-service-group: xiaojiang_tx_group
  datasource:
      url: jdbc:mysql://localhost:3306/seata_order
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver

logging:
  level:
    io:
      seata: info
feign:
  hystrix:
    enabled: false
mybatis:
  mapper-locations: classpath:mapper/*.xml

4、主启动

package com.xiaojiang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableDiscoveryClient
@EnableFeignClients
public class OrderModuleApplication2001 {
    public static void main(String[] args) {
        SpringApplication.run(OrderModuleApplication2001.class,args);
    }
}

5、domain

CommonResult

package com.xiaojiang.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult{
    private Integer code;
    private String message;
    private T data;
    public CommonResult(Integer code,String message){
        this(code,message,null);
    }
}

Order

package com.xiaojiang.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {
    private Long id;

    private Long userId;

    private Long productId;

    private Integer count;

    private BigDecimal money;

    /**
     * 订单状态:0:创建中;1:已完结
     */
    private Integer status;
}

6、dao

package com.xiaojiang.dao;

import com.xiaojiang.domain.Order;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface OrderMapper {

    void create(Order order);

    void update(@Param("userId") Long userId, @Param("status") Integer status);
}

xml




    
        
        
        
        
        
        
    
    
        insert into t_order(`id`, `user_id`, `product_id`, `count`, `money`, `status`)
        values (NULL, #{userId}, #{productId}, #{count}, #{money}, 0)
    
    
        UPDATE `t_order`
        SET status = 1
        WHERE user_id = #{userId} AND status = #{status};
    

7、service(feign)

OrderService

package com.xiaojiang.service;

import com.xiaojiang.domain.Order;

public interface OrderService {
    public void create(Order order);
}

OrderServiceImpl

package com.xiaojiang.service.Impl;

import com.xiaojiang.dao.OrderMapper;
import com.xiaojiang.domain.Order;
import com.xiaojiang.service.AccountService;
import com.xiaojiang.service.OrderService;
import com.xiaojiang.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    OrderMapper orderMapper;

    @Resource
    AccountService accountService;

    @Resource
    StorageService storageService;
    /**
     * 创建订单->调用库存服务扣减库存->调用账户服务扣减账户余额->修改订单状态
     * 简单说:
     * 下订单->减库存->减余额->改状态
     */
    @Override
    @GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("创建订单中------");
        orderMapper.create(order);
        log.info("创建订单成功-----");
        log.info("准备更新账户余额----");
        accountService.decrease(order.getUserId(),order.getMoney());
        log.info("更新完毕");
        log.info("准备更新库存------");
        storageService.decrease(order.getProductId(),order.getCount());
        log.info("更新完毕");
        orderMapper.update(order.getUserId(),0);
    }
}

AccountService

package com.xiaojiang.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;

@FeignClient(value = "seata-account-service")
public interface AccountService {
    @PostMapping("/account/decrease")
    public void decrease(@RequestParam("userId") Long userId,
                         @RequestParam("money")BigDecimal money);
}

StorageService

package com.xiaojiang.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
@FeignClient(value = "seata-storage-service")
public interface StorageService {
    @PostMapping("/storage/decrease")
    public void decrease(@RequestParam("productId") Long productId,
                         @RequestParam("count") Integer count);
}

8、controller

package com.xiaojiang.controller;

import com.xiaojiang.domain.CommonResult;
import com.xiaojiang.domain.Order;
import com.xiaojiang.service.OrderService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class OrderController {
    @Resource
    private OrderService orderService;

    @GetMapping(value = "/order/create")
    public CommonResult create(Order order){
        orderService.create(order);
        return new CommonResult(200,"订单创建成功");
    }
}

9、conf

DataSourceProxyConfig.java

package com.xiaojiang.conf;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;

/**
 * @auther zzyy
 * @create 2019-12-11 16:58
 * 使用Seata对数据源进行代理
 */
@Configuration
public class DataSourceProxyConfig {

    @Value("${mybatis.mapper-locations}")
    private String mapperLocations;

//    @Bean
//    @ConfigurationProperties(prefix = "spring.datasource")
//    public DataSource druidDataSource(){
//        return new DruidDataSource();
//    }
//
//    @Bean
//    public DataSourceProxy dataSourceProxy(DataSource dataSource) {
//        return new DataSourceProxy(dataSource);
//    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return sqlSessionFactoryBean.getObject();
    }

}




MybatisConfig

package com.xiaojiang.conf;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Configuration;

/**
 * @auther zzyy
 * @create 2019-12-11 16:57
 */
@Configuration
@MapperScan({"com.xiaojiang.dao"})
class MyBatisConfig {
}

10、file.conf和registry.conf

file.conf

transport {
  # tcp udt unix-domain-socket
  type = "TCP"
  #NIO NATIVE
  server = "NIO"
  #enable heartbeat
  heartbeat = true
  #thread factory for netty
  thread-factory {
    boss-thread-prefix = "NettyBoss"
    worker-thread-prefix = "NettyServerNIOWorker"
    server-executor-thread-prefix = "NettyServerBizHandler"
    share-boss-worker = false
    client-selector-thread-prefix = "NettyClientSelector"
    client-selector-thread-size = 1
    client-worker-thread-prefix = "NettyClientWorkerThread"
    # netty boss thread size,will not be used for UDT
    boss-thread-size = 1
    #auto default pin or 8
    worker-thread-size = 8
  }
  shutdown {
    # when destroy server, wait seconds
    wait = 3
  }
  serialization = "seata"
  compressor = "none"
}

service {

  vgroup_mapping.fsp_tx_group = "default" #修改自定义事务组名称

  default.grouplist = "127.0.0.1:8091"
  enableDegrade = false
  disable = false
  max.commit.retry.timeout = "-1"
  max.rollback.retry.timeout = "-1"
  disableGlobalTransaction = false
}


client {
  async.commit.buffer.limit = 10000
  lock {
    retry.internal = 10
    retry.times = 30
  }
  report.retry.count = 5
  tm.commit.retry.count = 1
  tm.rollback.retry.count = 1
}

## transaction log store
store {
  ## store mode: file、db
  mode = "db"

  ## file store
  file {
    dir = "sessionStore"

    # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
    max-branch-session-size = 16384
    # globe session size , if exceeded throws exceptions
    max-global-session-size = 512
    # file buffer size , if exceeded allocate new buffer
    file-write-buffer-cache-size = 16384
    # when recover batch read size
    session.reload.read_size = 100
    # async, sync
    flush-disk-mode = async
  }

  ## database store
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
    datasource = "dbcp"
    ## mysql/oracle/h2/oceanbase etc.
    db-type = "mysql"
    driver-class-name = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://localhost:3306/seata"
    user = "root"
    password = "123456"
    min-conn = 1
    max-conn = 3
    global.table = "global_table"
    branch.table = "branch_table"
    lock-table = "lock_table"
    query-limit = 100
  }
}
lock {
  ## the lock store mode: local、remote
  mode = "remote"

  local {
    ## store locks in user's database
  }

  remote {
    ## store locks in the seata's server
  }
}
recovery {
  #schedule committing retry period in milliseconds
  committing-retry-period = 1000
  #schedule asyn committing retry period in milliseconds
  asyn-committing-retry-period = 1000
  #schedule rollbacking retry period in milliseconds
  rollbacking-retry-period = 1000
  #schedule timeout retry period in milliseconds
  timeout-retry-period = 1000
}

transaction {
  undo.data.validation = true
  undo.log.serialization = "jackson"
  undo.log.save.days = 7
  #schedule delete expired undo_log in milliseconds
  undo.log.delete.period = 86400000
  undo.log.table = "undo_log"
}

## metrics settings
metrics {
  enabled = false
  registry-type = "compact"
  # multi exporters use comma divided
  exporter-list = "prometheus"
  exporter-prometheus-port = 9898
}

support {
  ## spring
  spring {
    # auto proxy the DataSource bean
    datasource.autoproxy = false
  }
}

registry.conf

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"

  nacos {
    serverAddr = "localhost:8848"
    namespace = ""
    cluster = "default"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = "0"
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
  }
  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
  type = "file"

  nacos {
    serverAddr = "localhost:8848"
    namespace = ""
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    app.id = "seata-server"
    apollo.meta = "http://192.168.1.204:8801"
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    session.timeout = 6000
    connect.timeout = 2000
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}


11、最终效果

SpringCloud Alibaba Seata处理分布式事务_第6张图片

 五、测试环境搭建之Storage-Module2002

以上一个模块为模板

pom,conf,主启动,domain中的CommonResult,和file.conf和registry.conf都一样,yml改服务名为

seata-storage-service

1、domin

Storage

package com.xiaojiang.domain;

import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Storage {
    private Long id;

    /**
     * 产品id
     */
    private Long productId;

    /**
     * 总库存
     */
    private Integer total;

    /**
     * 已用库存
     */
    private Integer used;

    /**
     * 剩余库存
     */
    private Integer residue;
}

2、dao

package com.xiaojiang.dao;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface StorageDao {
    public void decreaseSto(@Param("productId") Long productId,@Param("count") Integer count);
}

xml




    
        
        
        
        
        
    
    
        update t_storage
        set residue = residue - #{count},
            used = used + #{count}
        where product_id = #{productId}
    

3、service

StorageService

package com.xiaojiang.service;

public interface StorageService {
    public void decrease(Long productId,Integer count);
}

StorageServiceImpl.java

package com.xiaojiang.service.impl;

import com.xiaojiang.dao.StorageDao;
import com.xiaojiang.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StorageServiceImpl implements StorageService {
    @Autowired
    StorageDao storageDao;

    @Override
    public void decrease(Long productId, Integer count) {
        storageDao.decreaseSto(productId,count);
    }
}

4、controller(order中的feign配置要一致)

package com.xiaojiang.contorller;

import com.xiaojiang.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@RestController
public class StorageController {
    @Autowired
    StorageService storageService;

    @PostMapping("/storage/decrease")
    public void decrease(@RequestParam("productId") Long productId,
                         @RequestParam("count") Integer count){
        try {
            TimeUnit.SECONDS.sleep(20);
        }catch (Exception e){
            e.printStackTrace();
        }
        storageService.decrease(productId,count);
    }
}

5、最终效果

SpringCloud Alibaba Seata处理分布式事务_第7张图片

 六、测试环境搭建之Account-Module2003

以上一个模块为模板

pom,conf,主启动,domain中的CommonResult,和file.conf和registry.conf都一样,yml改服务名为

seata-storage-service

1、domin

Account

package com.xiaojiang.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
    private Long id;

    /**
     * 用户id
     */
    private Long userId;

    /**
     * 总额度
     */
    private BigDecimal total;

    /**
     * 已用额度
     */
    private BigDecimal used;

    /**
     * 剩余额度
     */
    private BigDecimal residue;
}

2、dao

package com.xiaojiang.dao;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.math.BigDecimal;

@Mapper
public interface AccountDao {
    public void decreaseACC(@Param("userId") Long userId, @Param("money") BigDecimal money);
}





    
        
        
        
        
        
    

    
        UPDATE t_account
        SET
            residue = residue - #{money},used = used + #{money}
        WHERE
            user_id = #{userId};
    


3、service

package com.xiaojiang.service;

import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;

public interface AccoutService {
    void decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money);
}

AccoutnSerice.java

package com.xiaojiang.service.Impl;

import com.xiaojiang.dao.AccountDao;
import com.xiaojiang.service.AccoutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
@Service
public class AccoutServiceImpl implements AccoutService {
    @Autowired
    private AccountDao accountDao;
    @Override
    public void decrease(Long userId, BigDecimal money) {
        accountDao.decreaseACC(userId,money);
    }
}

4、controller(与order中的feign配置匹配)

package com.xiaojiang.contorller;

import com.xiaojiang.service.AccoutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RestController
public class AccoutContorller {
    @Autowired
    private AccoutService accoutService;

    @PostMapping("/account/decrease")
    public void decrease(@RequestParam("userId") Long userId,
                         @RequestParam("money") BigDecimal money){
        accoutService.decrease(userId, money);
    }
}

5、最终效果

SpringCloud Alibaba Seata处理分布式事务_第8张图片

 七、测试

数据库初始

SpringCloud Alibaba Seata处理分布式事务_第9张图片

1、正常下单

http://localhost:2001/order/create?userId=1&productId=1&count=10&money=100

数据情况

SpringCloud Alibaba Seata处理分布式事务_第10张图片

 2、超时异常,没加@GlobalTransactional

为任意一个微服务添加一个延时

try {
    TimeUnit.SECONDS.sleep(20);
}catch (Exception e){
    e.printStackTrace();
}

故障情况

当库存和账户金额扣减后,订单状态并没有设置为已经完成,没有从零改为1

而且由于feign的重试机制,账户余额还有可能被多次扣减 

3、超时异常,加@GlobalTransactional

在OrderServiceImpl中的create的方法上添加

@Override
//name任意只要不重复即可,rollbackFor表示发生什么异常回滚事务,这里是所有异常
@GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
public void create(Order order) {

下单后发生异常数据库数据并没有任何改变,回滚事务成功

八、seata的运行机制

Simple Extensible Autonomous Transaction Architecture,简单可扩展自治事务框架

1、再看TC/TM/RM三大组件

SpringCloud Alibaba Seata处理分布式事务_第11张图片

具体流程

TM 开启分布式事务(TM 向 TC 注册全局事务记录);

按业务场景,编排数据库、服务等事务内资源(RM 向 TC 汇报资源准备状态 );

TM 结束分布式事务,事务一阶段结束(TM 通知 TC 提交/回滚分布式事务);

TC 汇总事务信息,决定分布式事务是提交还是回滚;

TC 通知所有 RM 提交/回滚 资源,事务二阶段结束。​

2、AT模式如何做到对业务的无侵入

SpringCloud Alibaba Seata处理分布式事务_第12张图片

一阶段加载

在一阶段,Seata 会拦截“业务 SQL”,
1  解析 SQL 语义,找到“业务 SQL”要更新的业务数据,在业务数据被更新前,将其保存成“before image”,
2  执行“业务 SQL”更新业务数据,在业务数据更新之后,
3  其保存成“after image”,最后生成行锁。
以上操作全部在一个数据库事务内完成,这样保证了一阶段操作的原子性。

SpringCloud Alibaba Seata处理分布式事务_第13张图片

二阶段提交

二阶段如是顺利提交的话,
因为“业务 SQL”在一阶段已经提交至数据库,所以Seata框架只需将一阶段保存的快照数据和行锁删掉,完成数据清理即可。

SpringCloud Alibaba Seata处理分布式事务_第14张图片

或二阶段回滚

二阶段如果是回滚的话,Seata 就需要回滚一阶段已经执行的“业务 SQL”,还原业务数据。
回滚方式便是用“before image”还原业务数据;但在还原前要首先要校验脏写,对比“数据库当前业务数据”和 “after image”,
如果两份数据完全一致就说明没有脏写,可以还原业务数据,如果不一致就说明有脏写,出现脏写就需要转人工处理。

SpringCloud Alibaba Seata处理分布式事务_第15张图片

SpringCloud Alibaba Seata处理分布式事务_第16张图片

你可能感兴趣的:(spring,分布式,spring,cloud)