微服务SpringCloud开弓之SpringCloud Alibaba Seata处理分布式事务「十五」

SpringCloud-Alibaba之Seata入门以及踩坑(二) 前言 上一篇文章:➣SpringCloud Alibaba之Seata入门以及踩坑(一)老顾介绍了seata相关的准备工作,以及版本的选择;今天老顾就来介绍一下seata的使用。以及在使用过程中遇到的问题。 案例背景 今天老顾介绍的案例场景也就是网上常用的场景,用户下单场景。整个流程就是用户下单时: 1)创建订单,订单状态为创建中 2)扣减商品库存 3)扣减用户金额 4)更改订单状态,订单状态为已完结 从以上业务流程,我们可以分为3个服务,如图 因为上面是3个分布式服务,事务问题就由此产生,我们来看看se 阅读详情

SpringCloud Alibaba Seata处理分布式事务

1、分布式事务问题

  • 分布式前

    单机单库没这个问题

    从1:1 -> 1:N -> N: N

  • 分布式之后

在这里插入图片描述
在这里插入图片描述

  • 一句话

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

2、Seata简介

官网地址

  • 是什么、

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

  • 能干嘛

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

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

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

    ​ 3组件概念

    • Transaction Coordinator(TC) :

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

    • Transaction Manager™

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

    • Resource Manager(RM)

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

处理过程

在这里插入图片描述
在这里插入图片描述- 下载地址

  • 怎么玩

    Spring 本地@Transactional

    全局@GlobalTransactional

2、Seata-Server安装

  • 官网地址

  • 下载版本1.1.0

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

    先备份原始file.conf文件

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

    file.conf

    service模块

    vgroup_mapping.my_test_tx_group = “fsp_tx_group”

    store模块

    mode = "db"
      url = "jdbc:mysql://127.0.0.1:3306/seata"
      user = "root"
      password = "你自己的密码"
    
  • mysql5.7数据库新建库seata

  • 在seata库里建表

    建表db_store.sql在\seata-server-1.1.0\seata\conf目录里面 db_store.sql

    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`)
    );
    
    
  • 修改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连接信息

  • 先启动Nacos端口号8848
  • 再启动seata-server

3、订单/库存/账户业务数据库准备

  • 以下演示都需要先启动Nacos后启动Seata,保证两个都OK

    Seata没启动报错no available server to connect

  • 分布式事务业务说明

    业务说明

在这里插入图片描述

下订单–>扣库存–>减账户(余额)

  • 创建业务数据库

    seata_order: 存储订单的数据库

    seata_storage:存储库存的数据库

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

  • 建表SQL

    CREATE DATABASE seata_order;
     
    CREATE DATABASE seata_storage;
     
    CREATE DATABASE seata_account;
    
  • 按照上述3库分别建对应业务表

    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库分别建对应的回滚日志表

    订单-库存-账户3个库下都需要建各自的回滚日志表

    \seata-server-1.1.0\seata\conf目录下的db_undo_log.sql

    SQL

    drop table `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;
    
  • 最终效果

在这里插入图片描述

4、订单/库存/账户业务微服务准备

  • 新建库新建订单Order-Module

    1.seata-order-service2001

    2.POM

     <dependencies>
            <!--nacos-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            </dependency>
            <!--seata-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
                <exclusions>
                    <exclusion>
                        <artifactId>seata-all</artifactId>
                        <groupId>io.seata</groupId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>io.seata</groupId>
                <artifactId>seata-all</artifactId>
                <version>1.0.0</version>
            </dependency>
            <!--feign-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
            <!--web-actuator-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            <!--mysql-druid-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.11</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
        </dependencies>
    

    3.YML

    server:
      port: 2001
    
    spring:
      application:
        name: seata-order-service
      cloud:
        alibaba:
          seata:
            #自定义事务组名称需要与seata-server中的对应
            tx-service-group: fsp_tx_group
        nacos:
          discovery:
            server-addr: localhost:8848
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://192.168.149.102:3306/seata_order
        username: root
        password: 123
    
    feign:
      hystrix:
        enabled: false
    
    logging:
      level:
        io:
          seata: info
    
    mybatis:
      mapperLocations: classpath:mapper/*.xml
    

    4.file.conf(seata配置)

    service {
      #transaction service group mapping
      vgroup_mapping.fsp_tx_group = "default"
      #only support when registry.type=file, please don't set multiple addresses
      default.grouplist = "127.0.0.1:8091"
      #disable seata
      disableGlobalTransaction = false
    }
    
    ## transaction log store, only used in seata-server
    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://192.168.149.102:3306/seata"
        user = "root"
        password = "123"
      }
    }
    

    5.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"
        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"
      }
    }
    

    6.domain

    • CommonResult
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class CommonResult<T>
    {
        private Integer code;
        private String  message;
        private T       data;
     
        public CommonResult(Integer code, String message)
        {
            this(code,message,null);
        }
    }
    
    • Order
    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;
     
        private Integer status; //订单状态:0:创建中;1:已完结
    }
    

    7.Dao接口及实现

    • OrderDao
    @Mapper
    public interface OrderDao {
    
        //创建订单
        void create(Order order);
    
        //修改订单状态
        void update(@Param("userId") Long userId, @Param("status") Integer status);
    }
    
    
    • resources文件夹下新建mapper文件夹后添加OrderMapper.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.atguigu.springcloud.alibaba.dao.OrderDao">
    
        <resultMap id="order" type="com.atguigu.springcloud.alibaba.domain.Order">
            <result property="id" column="id" jdbcType="BIGINT"/>
            <result property="user_id" column="userId" jdbcType="BIGINT"/>
            <result property="product_id" column="productId" jdbcType="BIGINT"/>
            <result property="count" column="count" jdbcType="INTEGER"/>
            <result property="money" column="money" jdbcType="BIGINT"/>
            <result property="status" column="status" jdbcType="INTEGER"/>
        </resultMap>
    
    
        <insert id="create">
            insert into t_order(user_id,product_id,count,money,status)
            value (#{userId},#{productId},#{count},#{money},0)
        </insert>
    
        <update id="update">
            update t_order set status = 1
            where user_id = #{userId} and status = #{status}
        </update>
    </mapper>
    

    8.Service接口及实现

    • OrderService

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

        @Service
        @Slf4j
        public class OrderServiceImpl implements OrderService {
        
            @Resource
            private OrderDao orderDao;
            @Resource
            private StorageService storageService;
            @Resource
            private AccountService accountService;
        //
        //    @GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
            @Override
            public void create(Order order) {
                log.info("-------->开始创建新订单");
                orderDao.create(order);
        
        
                log.info("--------订单微服务开始调用库存,做扣减");
                storageService.decrease(order.getProductId(),order.getCount());
                log.info("-------订单微服务开始调用库存,做扣减end");
        
                log.info("-------订单微服务开始调用账户,做扣减");
                accountService.decrease(order.getUserId(),order.getMoney());
                log.info("-------订单微服务开始调用账户,做扣减end");
        
        
                log.info("-------修改订单状态");
                orderDao.update(order.getUserId(),0);
                log.info("-------修改订单状态结束");
        
        
                log.info("--------下订单结束了,哈哈哈哈");
            }
        }
        
    • StorageService

      @FeignClient(value = "seata-storage-service")
      public interface StorageService{
          @PostMapping(value = "/storage/decrease")
          CommonResult decrease(@RequestParam("productId") Long productId, @RequestParam("count") Integer count);
      }
      
    • AccountService

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

    9.Controller

    @RestController
    public class OrderController{
        @Resource
        private OrderService orderService;
     
     
        @GetMapping("/order/create")
        public CommonResult create(Order order)
        {
            orderService.create(order);
            return new CommonResult(200,"订单创建成功");
        }
    }
    

    10.Config配置

    • MyBatisConfig

      @Configuration
      @MapperScan({"com.atguigu.springcloud.alibaba.dao"})
      public class MybatisConfig {
      }
      
    • DataSourceProxyConfig

      @Configuration
      public class DataSourceProxyConfig {
      
      //    @Value("${mybatis.mapperLocations}")
      //    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(DataSourceProxy dataSourceProxy) throws Exception {
              SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
              sqlSessionFactoryBean.setDataSource(dataSourceProxy);
              sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
      //        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
              sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
              return sqlSessionFactoryBean.getObject();
          }
      }
      

    11.主启动

    @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
    @EnableFeignClients
    @EnableDiscoveryClient
    public class SeataOrderMainApp2001 {
        public static void main(String[] args) {
            SpringApplication.run(SeataOrderMainApp2001.class,args);
        }
    }
    
  • 新建库存Storage-Module

    1.seata-order-service2002

    2.POM

        <dependencies>
            <!--nacos-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            </dependency>
            <!--seata-->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-seata</artifactId>
                <exclusions>
                    <exclusion>
                        <artifactId>seata-all</artifactId>
                        <groupId>io.seata</groupId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>io.seata</groupId>
                <artifactId>seata-all</artifactId>
                <version>1.0.0</version>
            </dependency>
            <!--feign-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
            <!--web-actuator-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            <!--mysql-druid-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.11</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
        </dependencies>
    

    3.YML

    server:
      port: 2002
    
    spring:
      application:
        name: seata-storage-service
      cloud:
        alibaba:
          seata:
            #自定义事务组名称需要与seata-server中的对应
            tx-service-group: fsp_tx_group
        nacos:
          discovery:
            server-addr: localhost:8848
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://192.168.149.102:3306/seata_storage
        username: root
        password: 123
    
    feign:
      hystrix:
        enabled: false
    
    logging:
      level:
        io:
          seata: info
    
    mybatis:
      mapperLocations: classpath:mapper/*.xml
    

    4.file.conf

    service {
      #transaction service group mapping
      vgroup_mapping.fsp_tx_group = "default"
      #only support when registry.type=file, please don't set multiple addresses
      default.grouplist = "127.0.0.1:8091"
      #disable seata
      disableGlobalTransaction = false
    }
    
    ## transaction log store, only used in seata-server
    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://192.168.149.102:3306/seata"
        user = "root"
        password = "123"
      }
    }
    

    5.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"
        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"
      }
    }
    
    

    6.domain

    • CommonResult

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

      @Data
      @NoArgsConstructor
      @AllArgsConstructor
      public class Storage {
      
          private Long id;
      
          // 产品id
          private Long productId;
      
          //总库存
          private Integer total;
      
      
          //已用库存
          private Integer used;
      
      
          //剩余库存
          private Integer residue;
      }
      

    7.Dao接口及实现

    • StorageDao

       
      @Mapper
      public interface StorageDao {
      
       
          //扣减库存信息
          void decrease(@Param("productId") Long productId, @Param("count") Integer count);
      }
      
    • resources文件夹下新建mapper文件夹后添加StorageMapper.xml

      <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
       
       
      <mapper namespace="com.atguigu.springcloud.alibaba.dao.StorageDao">
       
          <resultMap id="BaseResultMap" type="com.atguigu.springcloud.alibaba.domain.Storage">
              <id column="id" property="id" jdbcType="BIGINT"/>
              <result column="product_id" property="productId" jdbcType="BIGINT"/>
              <result column="total" property="total" jdbcType="INTEGER"/>
              <result column="used" property="used" jdbcType="INTEGER"/>
              <result column="residue" property="residue" jdbcType="INTEGER"/>
          </resultMap>
       
          <update id="decrease">
              UPDATE
                  t_storage
              SET
                  used = used + #{count},residue = residue - #{count}
              WHERE
                  product_id = #{productId}
          </update>
       
      </mapper>
      
      

    8.Service接口及实现

    • StorageService

      public interface StorageService {
          
           // 扣减库存
          void decrease(Long productId, Integer count);
      }
      
      • StorageServiceImpl

        @Service
        public class StorageServiceImpl implements StorageService {
         
            private static final Logger LOGGER = LoggerFactory.getLogger(StorageServiceImpl.class);
         
            @Resource
            private StorageDao storageDao;
         
             // 扣减库存
            @Override
            public void decrease(Long productId, Integer count) {
                LOGGER.info("------->storage-service中扣减库存开始");
                storageDao.decrease(productId,count);
                LOGGER.info("------->storage-service中扣减库存结束");
            }
        }
        

    9.Controller

    @RestController
    public class StorageController {
     
        @Autowired
        private StorageService storageService;
     
     
        //扣减库存
        @RequestMapping("/storage/decrease")
        public CommonResult decrease(Long productId, Integer count) {
            storageService.decrease(productId, count);
            return new CommonResult(200,"扣减库存成功!");
        }
    }
    

    10.Config配置 同订单Order-Module

    11.主启动

    @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
    @EnableDiscoveryClient
    @EnableFeignClients
    public class SeataStorageServiceApplication2002
    {
        public static void main(String[] args)
        {
            SpringApplication.run(SeataStorageServiceApplication2002.class, args);
        }
    }
    
  • 新建账户Account-Module

    1.seata-order-service2003

    2.POM 同上模块

    3.YML

    server:
      port: 2003
    
    spring:
      application:
        name: seata-account-service
      cloud:
        alibaba:
          seata:
            #自定义事务组名称需要与seata-server中的对应
            tx-service-group: fsp_tx_group
        nacos:
          discovery:
            server-addr: localhost:8848
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://192.168.149.102:3306/seata_account
        username: root
        password: 123
    
    feign:
      hystrix:
        enabled: false
    
    logging:
      level:
        io:
          seata: info
    
    mybatis:
      mapperLocations: classpath:mapper/*.xml
    

    4.file.conf 同上

    5.registry.conf 同上

    6.domain

    • CommonResult

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

      @Data
      @AllArgsConstructor
      @NoArgsConstructor
      public class Account {
       
          private Long id;
       
          /**
           * 用户id
           */
          private Long userId;
       
          /**
           * 总额度
           */
          private BigDecimal total;
       
          /**
           * 已用额度
           */
          private BigDecimal used;
       
          /**
           * 剩余额度
           */
          private BigDecimal residue;
      }
      

    7.Dao接口及实现

    • AccountDao

      @Mapper
      public interface AccountDao {
       
          /**
           * 扣减账户余额
           */
          void decrease(@Param("userId") Long userId, @Param("money") BigDecimal money);
      }
      
    • resources文件夹下新建mapper文件夹后添加AccountMapper.xml

      <?xml version="1.0" encoding="UTF-8" ?>
      <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
       
      <mapper namespace="com.atguigu.springcloud.alibaba.dao.AccountDao">
       
          <resultMap id="BaseResultMap" type="com.atguigu.springcloud.alibaba.domain.Account">
              <id column="id" property="id" jdbcType="BIGINT"/>
              <result column="user_id" property="userId" jdbcType="BIGINT"/>
              <result column="total" property="total" jdbcType="DECIMAL"/>
              <result column="used" property="used" jdbcType="DECIMAL"/>
              <result column="residue" property="residue" jdbcType="DECIMAL"/>
          </resultMap>
       
          <update id="decrease">
              UPDATE t_account
              SET
                residue = residue - #{money},used = used + #{money}
              WHERE
                user_id = #{userId};
          </update>
       
      </mapper>
      

    8.Service接口及实现

    • AccountService

       
      public interface AccountService {
       
          /**
           * 扣减账户余额
           */
          void decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money);
      }
      
    • AccountServiceImpl

      @Service
      public class AccountServiceImpl implements AccountService {
       
          private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class);
       
       
          @Resource
          AccountDao accountDao;
       
          /**
           * 扣减账户余额
           */
          @Override
          public void decrease(Long userId, BigDecimal money) {
              
               LOGGER.info("------->account-service中扣减账户余额开始");
              try { TimeUnit.SECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }
              accountDao.decrease(userId,money);
              LOGGER.info("------->account-service中扣减账户余额结束");
          }
      }
      

    9.Controller

    @RestController
    public class AccountController {
     
        @Resource
        AccountService accountService;
     
        /**
         * 扣减账户余额
         */
        @RequestMapping("/account/decrease")
        public CommonResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money){
            accountService.decrease(userId,money);
            return new CommonResult(200,"扣减账户余额成功!");
        }
    }
    

    10.Config配置 同其他模块

    11.主启动

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

    下订单->减库存->扣余额->改(订单)状态

在这里插入图片描述
数据库初始情况

在这里插入图片描述

正常下单

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

数据库情况
在这里插入图片描述

超时异常,没加@GlobalTransactional

AccountServiceImpl添加超时

   @Override
    public void decrease(Long userId, BigDecimal money) {
        log.info("账户扣除余额开始---");
        try {
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(userId);
        accountDao.decrease(userId, money);
        log.info("账户扣除余额结束---");
    }
}

结果

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

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

超时异常,添加@GlobalTransactional

  • AccountServiceImpl添加超时

  • OrderServiceImpl@GlobalTransactiona

  • 下单后数据库数据并没有任何改变

  • 记录都添加不进数据库

5、Seata之原理简介再次回顾

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

在这里插入图片描述

分布式事务的执行流程

  • TM开启分布式事务(TM向TC注册全局事务记录)
  • 换业务场景,编排数据库,服务等事务内资源(RM向TC汇报资源准备状态)
  • TM结束分布式事务,事务一阶段结束(TM通知TC提交/回滚分布式事务)
  • TC汇总事务信息,决定分布式事务是提交还是回滚
  • TC通知所有RM提交/回滚资源,事务二阶段结束。

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

是什么

在这里插入图片描述
一阶段加载
在这里插入图片描述
在这里插入图片描述
二阶段提交
在这里插入图片描述
二阶段回滚

在这里插入图片描述在这里插入图片描述

补充
在这里插入图片描述
在这里插入图片描述

微服务系列:分布式事务 Spring Cloud Alibaba 之 Seata 实战篇 这篇中我们就要项目实战中来使用 Seata 了,毕竟学习它就是为了实战中使用的。 其实 Seata 使用起来很简单,主要就是使用 @GlobalTransactional注解,但是搭建过程却还是稍微有点复杂的。 话不多说,开始今天的学习。 一、前言 本案例使用的是 Seata 的 AT 模式 由于篇幅有限,本文只贴出核心代码和配置,完整代码地址:cloud-seata: seata demo - Gitee.com 本案例使用 Nacos 作为注册中心,使用 Nacos 作为配置中心 1. 版本 阅读详情

相关推荐

SpringCloud集成Python服务

springcloud集成python的web服务,springcloud版本为最新版本Finchley.SR1,python版本3.6.3,包括了Ribbon负载均衡调用python服务等功能。

Spring cloud alibaba--Seata分布式事务

1.Seate是什么 Seate是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seate将为用户提供了AT、TCC、SAGA和XA事务模式,为用户打造一站式的分布式解决方案。AT模式是阿里首推的模式。 1.1seate的三大角色 TC(Transaction Coordinator)-事务协调者:维护全局和分支事务的状态,驱动全局事务提交或回滚 TM(Transaction Manager)-事务管理者:定义全局事务的范围,开始全局事务,提交或回滚全局事务。 RM(R

ZHANGLIZENG的博客 3729

CPU系统级验证——测试激励——imperas公司riscvOVPsimPlus文件分析

本分析重点关注该repo向量扩展部分。 1. repo简介 该repo是指令集验证的仿真环境包括,大部分是指令集的测试用例,也包含了一些模拟器,如riscvOVPsimPlus。 主要介绍的是riscvOVPsimPlus指令集模拟器,riscvOVPsimPlus(下面统称ISS)是imperas公司在riscvOVPsim基础上扩充了向量扩展的指令集模拟器,该repo于今年9月份部分开源 什么叫部分开源呢? 首先该repo必须在imperas官网注册下载,而且必须是企业用户(免费邮箱人家瞧不上.

知识,既贵,又便宜。 4459

SpringCloud Alibaba-Seata分布式事务

2PC是一个强一致性的同步阻塞协议,事务执⾏过程中需要将所需资源全部锁定,也就是俗称的 刚性事务。

沉浸式Study 2088

如何加快香山处理器Chisel->Verilog编译速度

相比使用默认的scala firrtl complier,使用CIRCT能够将香山代码编译到Verilog的速度提高50%左右。在执行make命令时加上MFC=1,例如make verilog MFC=1或make emu MFC=1。在本地从源码编译CIRCT,在编译完成后将circt/bin路径加入PATH中。使用GraalVM免费版作为JVM编译香山比OpenJDK快10%-20%。我们推荐使用GraalVM代替OpenJDK。使用CIRCT编译香山。

专业技术人员的归宿 862

YOLO11实战:手把手教你优化钢材表面缺陷识别模型(基于NEU-DET数据集)

本文详细介绍了如何使用YOLO11优化钢材表面缺陷识别模型,基于NEU-DET数据集进行实战训练。从数据增强、模型架构优化到训练过程控制,全面解析提升钢材缺陷检测性能的关键技术,特别针对裂纹、划痕等典型缺陷提出针对性解决方案。

weixin_29081163的博客 377

SpringBoot 整合 SpringCloud Alibab-Seata 详解

一、SpringBoot 整合 SpringCloud Alibab-Seata 详解。 二、Seata报错 can not get cluster name in registry config 'service.vgroupMapping.default_tx_group' 解决方案

博客 1万+

从零搭建一个AF架构项目:基于TIA Portal V19和S7-PLCSIM的仿真调试全流程

本文详细介绍了如何在TIA Portal V19环境中从零搭建西门子Automation Framework(AF架构)项目,包括环境准备、硬件组态、核心组件创建、项目架构分层实现以及仿真调试全流程。通过模块化编程和标准化接口设计,AF架构显著提升工业自动化项目的开发效率和维护便利性,特别适合S7-1500系列PLC的应用开发。

weixin_29313547的博客 672

SpringCloudAlibaba----Seata

1.什么是Seata:Seata 是一款开源的分布式事务解决方案,致力于在微服务架构下提供高性能和简单易用的分布式事务服务官方中文网:https://seata.io/zh-cngithub项目地址:https://github.com/seata/seataspringCloudAlibaba下使用:https://github.com/alibaba/spring-cloud-alibaba/tree/2.2.9.RELEASE2.Seata中的术语事务管理器。

Andy的java博客 807

立创开源PEX88048 8盘位M.2扩展卡硬件设计与PCIE4.0交换机应用解析

本文详细解析了基于Broadcom PEX88048 PCIe 4.0交换芯片的8盘位M.2扩展卡硬件设计。文章深入探讨了核心芯片选型、关键供电与安全设计、引脚配置、固件刷写方法,并重点剖析了PCIe 4.0时钟架构与高速PCB布局的核心思想,旨在帮助开发者理解如何设计高性能、高可靠性的存储扩展方案,并有效控制成本。

weixin_28949937的博客 616

【Unity】【VR】如何让Distance Grab抓取物品时限制物品的Rotation

VR中Canvas抓取旋转问题的解决方案 在VR应用中,Canvas作为UI面板常需被抓取拖动,但默认会随手柄产生Z轴旋转,导致UI歪斜。Unity的Rigidbody冻结旋转功能对此无效,因为XR抓取直接修改Transform而非物理模拟。

每日出拳老爷子的博客 611

spring cloud alibaba(看完即入门)——Seata篇

目录一、分布式理解1、理解CAP2、BASE理论3、分布式事务模型二、seata架构三、seata的部署与集成1、下载、配置、启动 一、分布式理解 1、理解CAP cap定理(分布式系统的三个指标): Consistency(一致性):用户访问分布式系统中的任意节点,得到的数据必须一致。 Avallabiry(可用性):用户访问集群中的任意健康节点,必须能得到响应,而不是超时或拒绝。 Partition tolerance(分区容错性): 分区:因为网络故障或其他原因导致分布式系统中的部分节点

qq_48721706的博客 1万+

数仓建模—数据治理框架选型

全名主要亮点覆盖面最广:从数据治理、架构、质量、安全到元数据、主数据、数据仓库等等,几乎所有数据管理主题都能在DMBOK里找到相应章节。概念权威统一:帮助组织建立通用术语和知识基础,减少“部门之间说法不一致”的沟通成本。适用场景:如果你所在公司(或团队)正准备系统梳理数据管理的方方面面,DMBOK是一份非常全面的指导手册,尤其适合培养新人或为整个组织统一认知。需要注意:DMBOK偏“知识指引”,不直接提供成熟度模型或实施路线图。想要落地,还需要结合其他评估模型或项目管理方法。小案例举例:某。

2401_84052244的博客 4743

SpringCloudAlibaba seata部署

部署指南 Seata新手部署指南(1.4.0版本) Seata分TC、TM和RM三个角色,TC(Server端)为单独服务端部署,TM和RM(Client端)由业务系统集成。 资源目录介绍 点击查看 client 存放client端sql脚本 (包含 undo_log表) ,参数配置 config-center 各个配置中心参数导入脚本,config.txt(包含server和client,原名nacos-config.txt)为通用参数文件 server server端数据库脚本 (

weixin_38582851的博客 1818

Juniper SRX PPPoE配置

set interfaces pp0 unit 1 ppp-options chap default-chap-secret 拨号用户名密码。set interfaces pp0 unit 0 ppp-options chap default-chap-secret 拨号密码。set interfaces pp0 unit 0 ppp-options chap local-name 拨号用户名。6号口接运营商进行拨号。

Jian Sun_的博客 750

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

SpringCloud Alibaba Seata (收藏版)

1,概念Seata是一款开源的分布式事务解决方案,致力于在微服务架构在提供高性能和简单一样的分布式事务服务。2,处理过程Transaction ID XID:全局唯一的事务IDTransaction Coordinator(TC) :维护全局和分支事务的状态,驱动全局事务提交或回滚。Transaction Manager™ :定义全局事务的范围:开始全局事务、提交或回滚全局事务。

sinat_53467514的博客 1298

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

Seata:Spring Cloud Alibaba分布式事务组件(非常详细)

服务启动时,从配置文件中获取服务分组的名称;从配置中心,通过事务分组名获取 TC 集群名;根据 TC 群组名以及其他信息构建服务名,获取真实的 TC 服务列表。

了解➔熟悉➔掌握➔精通 5817

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

【Spring Cloud】Spring Cloud Alibaba-- 分布式事务Seata原理

AT模式:无侵入式的分布式事务解决方案,适合不希望对业务进行改造的场景,但由于需要添加全局事务锁,对影响高并发系统的性能。该模式主要关注多DB访问的数据一致性,也包括多服务下的多DB数据访问一致性问题TCC模式:高性能的分布式事务解决方案,适用于对性能要求比较高的场景。该模式主要关注业务拆分,在按照业务横向扩展资源时,解决服务间调用的一致性问题Saga模式:长事务的分布式事务解决方案,适用于业务流程长且需要保证事务最终一致性的业务系统。

DreamSun的博客 2165

Spring Cloud Alibaba搭建(七):Seata

spring cloud alibaba关于seata学习笔记

你一定要站在自己所热爱的世界里,闪闪发亮。 1516

spring-cloud-starter-alibaba-seata使用说明

开发者可通过注解驱动快速实现分布式事务管理,结合 Nacos 注册中心与配置中心,构建高可用的微服务架构。依赖引入 → 配置调整 → 数据源代理 → 事务注解。实际应用中需特别注意版本兼容性、事务分组一致性及数据源代理配置,避免常见陷阱。

技术人集结地 1974

SpringCloudAlibaba集成seata(AT模式)、nacos

1、nacos作为注册中心 2、seata 2.1 去官网下载seata-1.2.0版本:下载中心 2.2 下载完进入到conf目录修改配置文件:registry.conf、file.conf 2.2.1 registry.conf文件: 注意:① type = "nacos",nacos作为注册中心写nacos,eureka作为注册中心写eureka; ②serverAddr = "localhost:8848" ,没有修改nacos端口号,可以这么写“serverAddr =..

你能找到这里,说明你有经天纬地之才,扭转乾坤只能,鬼神不测之计包藏宇宙之志,真乃乱世之枭雄,治世之能臣也 2551

SpringCloud学习(13)-SpringCloudAlibaba-Seata

Seata是阿里巴巴旗下的产品,是一款开源的分布式事务解决方案,旨在解决分布式事务问题。我们有必要先了解一下分布式事务:在微服务体系中,每一个模块都有连接一个数据库,这一点与单体项目是不同的,单体项目就连接一个数据库。那么如果有多个模块之间相互调用,怎样保证各个模块之间的事务一致性?由此引出了分布式事务。在同一个数据库中,我们要保证事物的一致性是很简单的。因为MySQL是基于单机事物的,所以一旦遇到跨库的场景,那么MySQL数据库就无能为力了。在这种情景下,seata蕴育而生。

dopapapa的博客 690

SpringCloud Alibaba-Seata

SpringCloud Alibaba-Seata

爱笑的boy的博客 1764

springcloud alibaba整合seata

双击seata-server.bat文件,cmd窗口会显示seata-server的启动情况。新建子模块alibaba-order-seata和alibaba-stock-seata。-- springcloud版本管理-->-- springboot版本管理-->-- alibaba版本管理-->此配置是将seata注册到注册中心,seata的配置持久化到配置中心。-- nacos服务注册发现 -->-- 添加openfeign的依赖-->

Spring_possible的博客 2000

【Spring Cloud】Spring Cloud Alibaba 实战 Seata (分布式事务)

Seata(Simple Extensible Autonomous Transaction Architecture) 是一款开源的分布式事务解决方案,致力于提供高性能和简单易用的分布式事务服务。Seata 将为用户提供了 AT、TCC、SAGA 和 XA 事务模式,为用户打造一站式的分布式解决方案。

DreamSun的博客 2653

Spring Cloud Alibaba 整合 Seata 实现分布式事务

本文介绍了整合分布式事务seta添加相关依赖配置配置,主要添加nacos配置中心和注册中心的配置。实现一个下单服务,先创建订单,然后扣减库存。库存不够,创建订单回滚。搭建服务完成之后,事务不回滚,对比官网实例项目。需要添加数据源代理,同时关闭据源自动代理。分布式事务就生效了。控制台一直报错,通过调试源码,找到问题的根源,这里学到了通过源码解决问题。以前前段时间一直在看源码,这次通过源码解决问题,努力还是会有收获的。

qq_42700121的博客 1397
上一篇: 微服务SpringCloud开弓之SpringCloud Alibaba Sentinel实现熔断与限流「十四」
下一篇: 负载均衡与网络底层刨析
漂吧
博客等级 码龄8年 15粉丝 38原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值