zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Seata分布式事务框架示例

2023-09-27 14:25:20 时间

一、背景

阿里给出了Seata的官方示例,地址: https://github.com/seata/seata-samples, 提供了很多示例:

本文以springboot-mybatis为例,该示例中有5个module:

  • sbm-account-service
  • sbm-business-service
  • sbm-common-service
  • sbm-order-service
  • sbm-storage-service

二、环境部署

2.1 mysql DB建表

示例中提供了mysql的建表语句,位置:seata-samples/springboot-mybatis/sql/all_in_one.sql

建了3个DB, 详情如下:

db table1 table2
db_account

account_tbl

undo_lob
db_order order_tbl undo_lob
db_stock stock_tbl undo_lob

2.2 Seata-Server 下载

官网下载:http://seata.io/zh-cn/blog/download.html

 

 

2.3 Seata-Server 配置

/conf/application.yml, seata3个节点(config、register、store)有多重配置方式,为了简单演示,这里采用默认file方式,其他方式可以参考application.example.yml

seata:
  config:
    # support: nacos, consul, apollo, zk, etcd3
    type: file
  registry:
    # support: nacos, eureka, redis, zk, consul, etcd3, sofa
    type: file
  store:
    # support: file 、 db 、 redis
    mode: file

2.4 Seata-Server 启动

sh /bin/seata-server.sh

启动日志:seata/logs/start.out

 

 

main] i.s.core.rpc.netty.NettyServerBootstrap  : Server started, service listen port: 8091

默认启动接口:8091

三、服务启动

分别启动4个服务,启动端口分别为:

server port
sbm-account-service 8083
sbm-order-service 8082
sbm-stock-service 8081
sbm-business-service 8084

 

四、测试

测试服务位置:sbm-business-service/src/main/java/io/seata/samples/business/controller/BusinessController.java

    /**
     * 购买下单,模拟全局事务提交
     *
     * @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;
    }

4.1 正常提交

http://localhost:8084/api/business/purchase/commit

4.2 异常提交

http://localhost:8084/api/business/purchase/rollback