seata(3):api实例源码

2023-09-20 16:57:55 浏览数 (1)

TM的代码位于src/main/java/io/seata/samples/api/Bussiness.java,TM开始执行前,先初始化各个RM

代码语言:javascript复制
        AccountService accountService = new AccountServiceImpl();
        StockService stockService = new StockServiceImpl();
        OrderService orderService = new OrderServiceImpl();
        orderService.setAccountService(accountService);

并且把数据设置成原始值

代码语言:javascript复制
        accountService.reset(userId, String.valueOf(money));
        stockService.reset(commodityCode, String.valueOf(commodityCount));
        orderService.reset(null, null);

注册TC 和RM的client

代码语言:javascript复制
        TMClient.init(applicationId, txServiceGroup);
        RMClient.init(applicationId, txServiceGroup);

然后就生成全局事务id,开启事务

代码语言:javascript复制
        GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate();
        try {
            tx.begin(6000, "testBiz");

紧接着就执行我们的事务,包括扣库存,生成订单,扣余额

代码语言:javascript复制
            stockService.deduct(commodityCode, opCount);
            orderService.create(userId, commodityCode, opCount);

            //check data if negative
            boolean needCommit = ((StockServiceImpl)stockService).validNegativeCheck("count", commodityCode)
                && ((AccountServiceImpl)accountService).validNegativeCheck("money", userId);

最后检查结果,根据执行结果决定提交还是回滚

代码语言:javascript复制
if (needCommit) {
    tx.commit();
} else {
    System.out.println("rollback trx, cause: data negative, xid is "   tx.getXid());
    tx.rollback();
}

具体到每一个RM的实现的时候,只需要实现对应的crud即可

src/main/java/io/seata/samples/api/service/impl/StockServiceImpl.java

代码语言:javascript复制

    @Override
    public void deduct(String commodityCode, int count) throws SQLException {
        String sql = "update stock_tbl set count = count - "   count   " where commodity_code = '"   commodityCode
              "'";
        DataSourceUtil.executeUpdate(DB_KEY, sql);
    }

src/main/java/io/seata/samples/api/service/impl/AccountServiceImpl.java

代码语言:javascript复制
    @Override
    public void reduce(String userId, int money) throws SQLException {
        String sql = "update account_tbl set money = money - "   money   " where user_id = '"   userId   "'";
        DataSourceUtil.executeUpdate(DB_KEY, sql);
    }

src/main/java/io/seata/samples/api/service/impl/OrderServiceImpl.java

代码语言:javascript复制
    @Override
    public void create(String userId, String commodityCode, Integer count) throws SQLException {
        int money = count * 200;
        String sql = "insert into order_tbl (user_id, commodity_code, count, money) values ('"   userId   "','"
              commodityCode   "',"   count   ","   money   ")";
        DataSourceUtil.executeUpdate(DB_KEY, sql);
        accountService.reduce(userId, money);

    }

整体来说,让分布式事务和本地事务使用起来一样方便,把事务管理的模式交给了TC,降低了系统复杂性的同时也抽象出了共性,让分布式事务处理中复杂的逻辑不再暴露给业务开发人员。

另一方面,TC作为一个中间件,对开发来说完全是黑盒,提升了运维成本,提高了稳定性风险。

0 人点赞