• 分布式事务-seata框架demo运行


    概述

    学习一个框架,我喜欢从demo中了解该框架所能达到的效果再进行深入地学习。本篇文章将会介绍 seata 的一个入门使用 demo ,作为使用 seata 的入门学习文章。

    使用案例

    首先到github 中下载一个 RM 的运行服务,本例中使用的是 :

    https://github.com/seata/seata/releases/download/v1.2.0/seata-server-1.2.0.zip

    解压后在 /bin 路径下启动 bat 文件

    接着自然就是demo 资源的下载了 :

    https://github.com/seata/seata-samples

    我们这里是使用的 MyBatis 和 Spring boot 和 seata 的整个案例,所涉及的 SQL 语句在 demo 路径下的 sql 文件夹下 :

    1297993-20200515143746918-279617761.png

    可以看到 springboot-mybatis 共有5个子项目,我们本地执行完sql ,记得修改每个子项目中的 application.yml 文件中关于数据库的配置 ,例如 :

    server:
      port: 8082
    spring:
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/db_order?useSSL=false&serverTimezone=UTC
        username: root
        password: 12345678
    seata:
        ....
        ....
    
    

    修改完启动,其中sbm-business-service 有个Controller 提供接口供我们测试 :

    @RequestMapping("/api/business")
    @RestController
    public class BusinessController {
    
        @Autowired
        private BusinessService businessService;
    
        /**
         * 购买下单,模拟全局事务提交
         *
         * @return
         */
        @RequestMapping("/purchase/commit")
        public Boolean purchaseCommit(HttpServletRequest request) {
            businessService.purchase("1001", "2001", 1);
            return true;
        }
    
        /**
         * 购买下单,模拟全局事务回滚
         *
         * @return
         */
        @RequestMapping("/purchase/rollback")
        public Boolean purchaseRollback() {
            try {
                businessService.purchase("1002", "2001", 1);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
    
            return true;
        }
    }
    

    可以看到这是一个模拟购物,订单和用户余额还有货物的例子,我们可以看一下数据库中的金额, 逻辑: 用户扣钱-> 库存-1 -> 订单库插入一条数据 这几个操作是不同事务,执行成功的话应该会同时一起执行,失败的话会一起回滚。 postman 调用 : localhost:8084/api/business/purchase/commit ,我们看一下执行成功后的结果 : db_account.account_tbl 表的数据

    id	user_id	money
    1	1001	9995
    2	1002	10000
    
    

    db_storage.storage_tbl 中的数据

    id	commodity_code	count
    1	2001	999
    

    db_order.order_tbl 表中的数据

    id	user_id	commodity_code	count	money
    1	1001	2001	1	5
    

    ok,事务执行是成功的。

    总结

    该篇只是简单地介绍 seata 框架demo 等简单使用,方便大家入门,后续将继续深入 seata 的学习

    参考资料

  • 相关阅读:
    H3C 12508 收集诊断信息
    hzwer收集课件笔记
    hzwer收集课件笔记
    Educational Codeforces Round 85 (Rated for Div. 2)
    Codeforces Round #632 (Div. 2)
    Codeforces Round #588 (Div. 2)
    Educational Codeforces Round 73 (Rated for Div. 2)
    Codeforces Round #631 (Div. 2)
    Codeforces Round #630 (Div. 2)
    复试准备
  • 原文地址:https://www.cnblogs.com/Benjious/p/12894972.html
Copyright © 2020-2023  润新知