SpringCloud之Seata

简介

  Seata组件是Spring Cloud Alibaba提供的处理分布式事务的组件。那何为分布式事务呢?在微服务环境下,假设有3个服务,A、B、C服务,A的某个方法,方法逻辑是通过OpenFeign调用B服务的方法,再通过OpenFeign调用C服务的方法,最后再执行自身的业务逻辑,对数据库执行操作。那如果在对数据库执行操作时出现异常,此时要进行回滚,即调用B服务的方法和调用C服务的方法中,对数据库的操作,要进行回滚。如果没有分布式事务的介入,B、C服务对数据库的操作是无法回滚的。但有了Seata,这个问题便可得到解决。

四种模式

  Seata为我们提供了AT、TCC、SAGA、XA这四种模式,不同模式针对不同的场景需求,提供解决方案。
  AT模式:即自动模式,可以解决80%的分布式事务需求,依赖数据库的undo log和redo log。
  TCC模式:当某服务操作的数据库是非关系型数据库时,如Redis,就不能用AT模式了,而是使用TCC模式。各服务的逻辑层代码中,编写一组三个方法(prepare、commit、rollback),prepare是无论事务成功与否都要执行的方法,commit是整体事务成功时执行的方法,rollback是整体事务失败时执行的方法
  SAGA模式:针对于老项目:编写一个类,当事务失败要进行回滚时,运行这个编写的回滚类。这样子就不用修改原有的代码了。
  XA模式:使用较少,强一致性的。

代码示例

  首先下载seata:https://github.com/seata/seata/releases
  作者这里下载的是1.4.2的windows版本,

SpringCloud之Seata_第1张图片

  下载好后,解压,打开conf文件夹下的registry.conf,

SpringCloud之Seata_第2张图片

  该文件下方还有个config配置,type为file,而这个file指向的是和registry.conf同目录下的file.conf,我们打开编辑它:

SpringCloud之Seata_第3张图片

SpringCloud之Seata_第4张图片

  如果你用的是mysql8,driverClassName要改成"com.mysql.cj.jdbc.Driver",url后面要加上"&serverTimezone=Asia/Shanghai",user、password也要改成自己数据库的用户名和密码。在mysql上建立seata数据库(不叫seata也行,但要和url中的名称保持一致),然后新建3张表,global_table、branch_table、lock_table,sql如下:

-- 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_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 `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 `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_and_branch_id` (`xid` , `branch_id`)
) ENGINE = InnoDB
  DEFAULT CHARSET = utf8mb4;

  然后先启动nacos,再启动seata(点击bin目录下的seata-server.bat);如果在nacos的服务列表中,多出来一条数据,说明刚才的配置成功奏效了:

SpringCloud之Seata_第5张图片

  下面我们要新建2个服务模块,订单模块和库存模块;订单模块的某个方法,会通过OpenFeign调用库存模块的方法,这个库存模块的方法会减少库存表的数量1;然后再往自身的订单表新增一条数据。我们首先建立库存模块:

  引入依赖:

<dependencies>
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druid-spring-boot-starterartifactId>
        <version>1.2.8version>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
    dependency>
    <dependency>
        <groupId>org.mybatis.spring.bootgroupId>
        <artifactId>mybatis-spring-boot-starterartifactId>
        <version>2.2.2version>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>

    <dependency>
        <groupId>com.alibaba.cloudgroupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery
        artifactId>
    dependency>
    <dependency>
        <groupId>com.alibaba.cloudgroupId>
        <artifactId>spring-cloud-starter-alibaba-seataartifactId>
    dependency>
dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-alibaba-dependenciesartifactId>
            <version>2.2.6.RELEASEversion>
            <type>pomtype>
            <scope>importscope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-dependenciesartifactId>
            <version>2.2.6.RELEASEversion>
            <type>pomtype>
            <scope>importscope>
        dependency>
    dependencies>
dependencyManagement>

  application.yml的配置:

server:
  port: 8081

spring:
  application:
    name: seata-stock
  # 不能放在bootstrap.yml中,不然启动报错
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai
      username: root
      password: 123456
      type: com.alibaba.druid.pool.DruidDataSource
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

mybatis:
  # xml文件必须放在src/main/resources下的mapper文件夹下;
  # 或者xml文件和mapper接口同名、同路径,不需要配置
  mapper-locations: classpath*:mapper/*.xml

seata:
  # 事务组名称
  tx-service-group: mygroup
  service:
    vgroup-mapping:
      mygroup: default

  Controller层:

import com.gs.seatastock.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/stock")
public class StockController {

    @Autowired
    private StockService stockService;

    @RequestMapping("/desc")
    public void desc() {
        stockService.desc(1);
    }

}

  Service层:

public interface StockService {

    void desc(Integer productId);

}
import com.gs.seatastock.mapper.StockMapper;
import com.gs.seatastock.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class StockServiceImpl implements StockService {

    @Autowired
    private StockMapper stockMapper;

    public void desc(Integer productId) {
        stockMapper.stockDesc(productId);
    }

}

  mapper层:

import org.apache.ibatis.annotations.Param;

public interface StockMapper {

    Integer stockDesc(@Param("productId") Integer productId);

}

  xml文件:

<update id="stockDesc">
    update stock set count = count - 1 where product_id = #{productId}
update>

  数据库层面,Stock表:

CREATE TABLE `stock` (
  `id` int NOT NULL AUTO_INCREMENT,
  `product_id` int DEFAULT NULL,
  `count` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `stock_un` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;

  并且插入一条数据:

insert into stock (product_id, count) values(1, 100);

  数据库下也要给seata建立一张名为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,
 
PRIMARY KEY (`id`),
 
UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
 
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

  再建立订单模块,引入依赖:
<dependencies>
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druid-spring-boot-starterartifactId>
        <version>1.2.8version>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
    dependency>
    <dependency>
        <groupId>org.mybatis.spring.bootgroupId>
        <artifactId>mybatis-spring-boot-starterartifactId>
        <version>2.2.2version>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>

    <dependency>
        <groupId>com.alibaba.cloudgroupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery
        artifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-openfeignartifactId>
        <version>2.2.6.RELEASEversion>
    dependency>
    <dependency>
        <groupId>com.alibaba.cloudgroupId>
        <artifactId>spring-cloud-starter-alibaba-seataartifactId>
    dependency>
dependencies>

  application.yml的配置:

server:
  port: 8082

spring:
  application:
    name: seata-order
  # 不能放在bootstrap.yml中,不然启动报错
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/test1?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai
      username: root
      password: 123456
      type: com.alibaba.druid.pool.DruidDataSource
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

mybatis:
  # xml文件必须放在src/main/resources下的mapper文件夹下;
  # 或者xml文件和mapper接口同名、同路径,不需要配置
  mapper-locations: classpath*:mapper/*.xml

seata:
  # 事务组名称
  tx-service-group: mygroup
  service:
    vgroup-mapping:
      mygroup: default

  Controller层(这里有个重要的seata注解:@GlobalTransactional):
import com.gs.seataorder.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;


    @RequestMapping("/createOrder")
    @GlobalTransactional
    public void createOrder() {
        orderService.createOrder(1);
    }

}

  Service层:

public interface OrderService {

    Integer createOrder(Integer productId);

}
import com.gs.seataorder.feign.MyFeignClient;
import com.gs.seataorder.mapper.OrderMapper;
import com.gs.seataorder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private MyFeignClient feignClient;

    @Autowired
    private OrderMapper mapper;


    public Integer createOrder(Integer productId) {
        feignClient.desc();
        int i = 1 / 0;
        return mapper.createOrder(productId);
    }
}

  Feign的接口:

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

@FeignClient(value = "seata-stock")
public interface MyFeignClient {

    @GetMapping("/stock/desc")
    void desc();

}

  mapper层:

import org.apache.ibatis.annotations.Param;

public interface OrderMapper {

    Integer createOrder(@Param("productId") Integer productId);

}

  xml文件:

    <insert id="createOrder">
        insert into orderForm(product_id, count) values(#{productId}, 1) 
        on duplicate key update count = count + 1
    insert>

  数据库的orderForm表:

CREATE TABLE `orderform` (
  `id` int NOT NULL AUTO_INCREMENT,
  `product_id` int DEFAULT NULL,
  `count` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `orderForm_un` (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;

  undo_log表也不能少,建表的sql和上面的一样。

  打开浏览器去访问:http://localhost:8082/order/createOrder,然后去观察stock表和orderform表;stock表的count字段没有减少,还是100,orderform表没有增加数据,说明此时分布式事务成功了。


  以上的代码示例,是基于AT模式的;想要尝试其余模式的,可以参考:

  TCC模式:
  https://seata.io/zh-cn/blog/integrate-seata-tcc-mode-with-spring-cloud.html

  SAGA模式:
  https://seata.io/zh-cn/docs/user/saga.html

  XA模式:
  https://github.com/seata/seata-samples

你可能感兴趣的:(#,SpringCloud,spring,cloud,java)