程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-06(2)

分布式事务(3)

发布于2021-06-12 14:32     阅读(338)     评论(0)     点赞(27)     收藏(1)


1、分布式事务解决方案之TCC

1.1 什么是 TCC 事务

TCC是Try、Confirm、Cancel三个词语的缩写,TCC要求每个分支事务实现三个操作:预处理Try、确认Confirm、撤销Cancel。Try操作做业务检查及资源预留,Confirm做业务确认操作,Cancel实现一个与Try相反的操作即回滚操作。TM首先发起所有的分支事务的try操作,任何一个分支事务的try操作执行失败,TM将会发起所有分支事务的Cancel操作,若try操作全部成功,TM将会发起所有分支事务的Confirm操作,其中Confirm/Cancel操作若执行失败,TM会进行重试。

在这里插入图片描述

分支事务失败的情况:
在这里插入图片描述
TCC 分为三个阶段:

  • Try 阶段是做业务检查(一致性)及资源预留(隔离),此阶段是一个初步操作,它和后续的Confirm 一起才能真正构成一个完整的业务逻辑。
  • Confirm 阶段是做确认提交,Try阶段所有分支事务执行成功后开始执行Confirm。通常情况下,采用TCC 则认为Confirm阶段是不会出错的。即:只要Try成功,Confirm一定成功。若Confirm阶段真的出错了,需要引入重试机制或人工处理。
  • Cancel 阶段实在业务执行错误需要回滚的情况下执行分支事务的业务取消,预留资源的释放。通常情况下,采用TCC则认为Cancel阶段也是一定成功的。若Cancel阶段真的出错了,需要引入重试机制或人工处理。
  • TM事务管理器
    TM事务管理器可以实现独立的服务,也可以让全局事务发起方充当TM角色,TM独立出来是为了称为公用组件,是为了考虑系统结构和软件复用。
    TM再发起全局事务时生成全局事务记录,全局事务ID贯穿整个分布式事务的调用链路,用来记录事务上下文,追踪和记录状态,由于Confirm和Cancel失败需要重试,因此需要实现幂等,幂等性是指同一个操作无论请求多少次,其结果都是相同的。

1.2 TCC 解决方案

上一节所讲的Seata也支持TCC,但Seata的TCC模式对Spring Cloud并没有提供支持。我们的目标是理解TCC的原理以及事务协调运作的过程,因此更请倾向于轻量级易于理解的框架,因此最终确定了Hmily

Hmily是一个高性能分布式事务TCC开源框架。基于Java语言来开发(JDK1.8),支持Dubbo,Spring Cloud等RPC框架进行分布式事务。它目前支持以下特性:

  • 支持嵌套事务(Nested transaction support).
  • 采用disruptor框架进行事务日志的异步读写,与RPC框架的性能毫无差别。
  • 支持SpringBoot-starter 项目启动,使用简单。
  • RPC框架支持 : dubbo,motan,springcloud。
  • 本地事务存储支持 : redis,mongodb,zookeeper,file,mysql。
  • 事务日志序列化支持:java,hessian,kryo,protostuff。
  • 采用Aspect AOP 切面思想与Spring无缝集成,天然支持集群。
  • RPC事务恢复,超时异常恢复等。

Hmily利用AOP对参与分布式事务的本地方法与远程方法进行拦截处理,通过多方拦截,事务参与者能透明的调用到另一方的Try、Confirm、Cancel方法;传递事务上下文;并记录事务日志,酌情进行补偿,重试等。

Hmily不需要事务协调服务,但需要提供一个数据库(mysql/mongodb/zookeeper/redis/file)来进行日志存储。

Hmily实现的TCC服务与普通的服务一样,只需要暴露一个接口,也就是它的Try业务。Confirm/Cancel业务逻辑,只是因为全局事务提交/回滚的需要才提供的,因此Confirm/Cancel业务只需要被Hmily TCC事务框架发现即可,不需要被调用它的其他业务服务所感知。

官网介绍:https://dromara.org/zh/projects/hmily/user-springcloud/

TCC需要注意三种异常处理分别是空回滚、幂等、悬挂:

空回滚

在没有调用 TCC 资源 Try 方法的情况下,调用了二阶段的 Cancel 方法,Cancel 方法需要识别出这是一个空回滚,然后直接返回成功。

出现原因是当一个分支事务所在服务宕机或网络异常,分支事务调用记录为失败,这个时候其实是没有执行Try阶段,当故障恢复后,分布式事务进行回滚则会调用二阶段的Cancel方法,从而形成空回滚。

解决思路是关键就是要识别出这个空回滚。思路很简单就是需要知道一阶段是否执行,如果执行了,那就是正常回滚;如果没执行,那就是空回滚。前面已经说过TM在发起全局事务时生成全局事务记录,全局事务ID贯穿整个分布式事务调用链条。再额外增加一张分支事务记录表,其中有全局事务 ID 和分支事务 ID,第一阶段 Try 方法里会插入一条记录,表示一阶段执行了。Cancel 接口里读取该记录,如果该记录存在,则正常回滚;如果该记录不存在,则是空回滚。

幂等

通过前面介绍已经了解到,为了保证TCC二阶段提交重试机制不会引发数据不一致,要求 TCC 的二阶段 Try、Confirm 和 Cancel 接口保证幂等,这样不会重复使用或者释放资源。如果幂等控制没有做好,很有可能导致数据不一致等严重问题。

解决思路在上述“分支事务记录”中增加执行状态,每次执行前都查询该状态。

悬挂

悬挂就是对于一个分布式事务,其二阶段 Cancel 接口比 Try 接口先执行。

出现原因是在 RPC 调用分支事务try时,先注册分支事务,再执行RPC调用,如果此时 RPC 调用的网络发生拥堵,通常 RPC 调用是有超时时间的,RPC 超时以后,TM就会通知RM回滚该分布式事务,可能回滚完成后,RPC 请求才到达参与者真正执行,而一个 Try 方法预留的业务资源,只有该分布式事务才能使用,该分布式事务第一阶段预留的业务资源就再也没有人能够处理了,对于这种情况,我们就称为悬挂,即业务资源预留后没法继续处理。

解决思路是如果二阶段执行完成,那一阶段就不能再继续执行。在执行一阶段事务时判断在该全局事务下,“分支事务记录”表中是否已经有二阶段事务记录,如果有则不执行Try。

举例,场景为 A 转账 30 元给 B,A和B账户在不同的服务。

方案1:

账户A

try:
	检查余额是否够30元
	扣减30元
confirm:
	空
cancel:
	增加30

账户B

try:
	增加30元
confirm:
	空
cancel:
	减少30

方案一说明:

  • 账户A,这里的余额就是所谓的业务资源,按照前面提到的原则,在第一阶段需要检查并预留业务资源,因此,我们在扣钱 TCC 资源的 Try 接口里先检查 A 账户余额是否足够,如果足够则扣除 30 元。 Confirm 接口表示正式提交,由于业务资源已经在 Try 接口里扣除掉了,那么在第二阶段的 Confirm 接口里可以什么都不用做。Cancel接口的执行表示整个事务回滚,账户A回滚则需要把 Try 接口里扣除掉的 30 元还给账户。
  • 2)账号B,在第一阶段 Try 接口里实现给账户B加钱,Cancel 接口的执行表示整个事务回滚,账户B回滚则需要把Try 接口里加的 30 元再减去。

方案1的问题分析:

  • 1)如果账户A的try没有执行在cancel则就多加了30元。
  • 2)由于try,cancel、confirm都是由单独的线程去调用,且会出现重复调用,所以都需要实现幂等。
  • 3)账号B在try中增加30元,当try执行完成后可能会其它线程给消费了。
  • 4)如果账户B的try没有执行在cancel则就多减了30元。

问题解决:

  • 1)账户A的cancel方法需要判断try方法是否执行,正常执行try后方可执行cancel。
  • 2)try,cancel、confirm方法实现幂等。
  • 3)账号B在try方法中不允许更新账户金额,在confirm中更新账户金额。
  • 4)账户B的cancel方法需要判断try方法是否执行,正常执行try后方可执行cancel。

优化方案:

账户A

trytry幂等校验
	try悬挂处理
	检查余额是否够30元
	扣减30元
confirm:
	空
cancel:
	cancel幂等校验
	cancel空回滚处理
	增加30

账户B

try:
	空
confirm:
	confirm幂等校验
	正式增加30元
cancel:
	空

1.3 Hmily 实现 TCC 事务

1.3.1 业务说明

本实例通过Hmily实现TCC分布式事务,模拟两个账户的转账交易过程。

两个账户分别在不同的银行(张三在bank1、李四在bank2),bank1、bank2是两个微服务。

交易过程是,张三给李四转账指定金额。

上述交易步骤,要么一起成功,要么一起失败,必须是一个整体性的事务。

在这里插入图片描述

1.3.2 程序组成部分

数据库:MySQL-5.7.25

JDK:64位 jdk1.8.0_201

微服务:spring-boot-2.1.3、spring-cloud-Greenwich.RELEASE

Hmily:hmily-springcloud.2.0.4-RELEASE

微服务及数据库的关系:

tcc-bank1-server 银行1,操作张三账户,连接数据库bank1

tcc-bank2-server 银行2,操作李四账户,连接数据库bank2

服务注册中心:nacos 注册中心

1.3.3 创建数据库

创建 hmily 数据库,用于存储 hmily 框架记录的数据。

CREATE DATABASE `hmily` 
CHARACTER SET 'utf8' 
COLLATE 'utf8_general_ci';

创建bank1库,并导入以下表结构和数据(包含张三账户)

创建bank2库,并导入以下表结构和数据(包含李四账户)

与上述 seata 中数据库一致。

每个数据库都创建try、confirm、cancel三张日志表:

CREATE TABLE `local_try_log` (  
`tx_no` varchar(64) NOT NULL COMMENT '事务id',  
`create_time` datetime DEFAULT NULL,  
PRIMARY KEY (`tx_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `local_confirm_log` (  
`tx_no` varchar(64) NOT NULL COMMENT '事务id',  
`create_time` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `local_cancel_log` (  
`tx_no` varchar(64) NOT NULL COMMENT '事务id',  
`create_time` datetime DEFAULT NULL,  
PRIMARY KEY (`tx_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

1.3.4 创建tcc-bank1-serrver

application.yml

server:
  port: 2006
spring:
  application:
    name: hmily-bank1-server
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/bank1?useSSL=false
    driver-class-name: org.gjt.mm.mysql.Driver
    type: com.alibaba.druid.pool.DruidDataSource
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848


org:
  dromara:
    hmily :
      serializer : kryo
      recoverDelayTime : 30
      retryMax : 30
      scheduledDelay : 30
      scheduledThreadMax :  10
      repositorySupport : db
      started: true
      hmilyDbConfig :
        driverClassName: com.mysql.jdbc.Driver
        url :  jdbc:mysql://localhost:3306/hmily?useUnicode=true&useSSL=false
        username : root
        password : 123456

feign:
  hystrix:
    enabled: true


mybatis:
  mapper-locations: classpath:/mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
  level:
    io:
      seata: info

config

package com.yao.hmily.config;


import org.dromara.hmily.common.config.HmilyDbConfig;
import org.dromara.hmily.core.bootstrap.HmilyTransactionBootstrap;
import org.dromara.hmily.core.service.HmilyInitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.env.Environment;


/**
 * 数据源代理
 * @author yao
 */
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class HmilyConfiguration {

    @Autowired
    private Environment env;


    @Bean
    public HmilyTransactionBootstrap hmilyTransactionBootstrap(HmilyInitService hmilyInitService){
        HmilyTransactionBootstrap hmilyTransactionBootstrap = new HmilyTransactionBootstrap(hmilyInitService);
        hmilyTransactionBootstrap.setSerializer(env.getProperty("org.dromara.hmily.serializer"));
        hmilyTransactionBootstrap.setRecoverDelayTime(Integer.parseInt(env.getProperty("org.dromara.hmily.recoverDelayTime")));
        hmilyTransactionBootstrap.setRetryMax(Integer.parseInt(env.getProperty("org.dromara.hmily.retryMax")));
        hmilyTransactionBootstrap.setScheduledDelay(Integer.parseInt(env.getProperty("org.dromara.hmily.scheduledDelay")));
        hmilyTransactionBootstrap.setScheduledThreadMax(Integer.parseInt(env.getProperty("org.dromara.hmily.scheduledThreadMax")));
        hmilyTransactionBootstrap.setRepositorySupport(env.getProperty("org.dromara.hmily.repositorySupport"));
        hmilyTransactionBootstrap.setStarted(Boolean.parseBoolean(env.getProperty("org.dromara.hmily.started")));
        HmilyDbConfig hmilyDbConfig = new HmilyDbConfig();
        hmilyDbConfig.setDriverClassName(env.getProperty("org.dromara.hmily.hmilyDbConfig.driverClassName"));
        hmilyDbConfig.setUrl(env.getProperty("org.dromara.hmily.hmilyDbConfig.url"));
        hmilyDbConfig.setUsername(env.getProperty("org.dromara.hmily.hmilyDbConfig.username"));
        hmilyDbConfig.setPassword(env.getProperty("org.dromara.hmily.hmilyDbConfig.password"));
        hmilyTransactionBootstrap.setHmilyDbConfig(hmilyDbConfig);
        return hmilyTransactionBootstrap;
    }
}

dao

package com.yao.hmily.dao;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface AccountInfoDao {

    //张三扣减金额
    /**
     *
     * @param accountNo  银行卡号
     * @param amount  转账金额
     * @return
     */
    int reduceAccountBalance(@Param("accountNo") String accountNo,
                             @Param("amount") Double amount);


    //张三增加金额
    /**
     *
     * @param accountNo  银行卡号
     * @param amount  转账金额
     * @return
     */
    int addAccountBalance(@Param("accountNo") String accountNo,
                          @Param("amount") Double amount);



    /**
     * 增加某分支事务try执行记录
     * @param localTradeNo 本地事务编号
     * @return
     */
    int addTry(@Param("txNo") String localTradeNo);

    /**
     * 增加某分支事务confirm执行记录
     * @param localTradeNo 本地事务编号
     * @return
     */
    int addConfirm(@Param("txNo") String localTradeNo);

    /**
     * 增加某分支事务cancel执行记录
     * @param localTradeNo 本地事务编号
     * @return
     */
    int addCancel(@Param("txNo") String localTradeNo);

    /**
     * 查询分支事务try是否已执行
     * @param localTradeNo 本地事务编号
     * @return
     */
    int isExistTry(@Param("txNo") String localTradeNo);
    /**
     * 查询分支事务confirm是否已执行
     * @param localTradeNo 本地事务编号
     * @return
     */
    int isExistConfirm(@Param("txNo") String localTradeNo);

    /**
     * 查询分支事务cancel是否已执行
     * @param localTradeNo 本地事务编号
     * @return
     */
    int isExistCancel(@Param("txNo") String localTradeNo);

}

mapper.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.yao.hmily.dao.AccountInfoDao" >


    <update id="reduceAccountBalance">
        update account_info
        set
                account_balance = account_balance - #{amount}
        WHERE
                account_balance >= #{amount}
        and
                account_no = #{accountNo}
    </update>

    <update id="addAccountBalance">
        update account_info
        set
                account_balance = account_balance + #{amount}
        WHERE
                account_no = #{accountNo}
    </update>

    <insert id="addTry">
        insert into
                local_try_log
        values (#{txNo},now())
    </insert>

    <insert id="addConfirm">
        insert into
                local_confirm_log
        values (#{txNo},now());
    </insert>

    <insert id="addCancel" >
        insert into
                local_cancel_log
        values (#{txNo},now());
    </insert>

    <select id="isExistTry" resultType="int">
        select
                count(1)
        from
                local_try_log
        where
                tx_no = #{txNo}
    </select>

    <select id="isExistConfirm" resultType="int">
        select
                count(1)
        from
                local_confirm_log
        where
                tx_no = #{txNo}
    </select>

    <select id="isExistCancel" resultType="int">
        select
                count(1)
        from
                local_cancel_log
        where
                tx_no = #{txNo}
    </select>
</mapper>

feign 远程调用

package com.yao.hmily.service;

import com.yao.hmily.domain.CommonResult;
import org.dromara.hmily.annotation.Hmily;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(value = "hmily-bank2-server")
public interface Bank2Service {

    //张三转账
    @GetMapping("/transfer/{amount}")
    @Hmily
    CommonResult transfer(@PathVariable("amount") Double amount);
}

业务类

package com.yao.hmily.service.impl;


import com.yao.hmily.dao.AccountInfoDao;
import com.yao.hmily.domain.CommonResult;
import com.yao.hmily.service.Bank2Service;
import lombok.extern.slf4j.Slf4j;

import org.dromara.hmily.annotation.Hmily;
import org.dromara.hmily.core.concurrent.threadlocal.HmilyTransactionContextLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yao.hmily.service.AccountInfoService;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AccountInfoServiceImpl implements AccountInfoService {

    @Autowired
    private AccountInfoDao accountInfoDao;

    @Autowired
    private Bank2Service bank2Service;

    /**
     * 账户扣款,就是 tcc 的 try 方法
     * try幂等校验
     * try悬挂处理
     * 检查余额是否够30元
     * 扣减30元
     * @param accountNo
     * @param amount
     * @return
     */
    @Override
    @Hmily(confirmMethod = "commit",cancelMethod = "rollback") //只要标记这个注解就是 try 方法,在注解中指定confirm,cancel 两个方法名字
    @Transactional
    public void updateAccountBalance(String accountNo, Double amount) {

        //获取全局事务 ID
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("bank1 try begin 开始执行了 xid():"+transId);
        //幂等判断:判断local_try_log表中是否有try日志记录,如果有则不再执行
        if (accountInfoDao.isExistTry(transId) > 0){
            log.info("bank1 幂等处理 try 已经执行,无需重复执行,xid():"+transId);
            return ;
        }

        //悬挂处理:如果cancel、confirm有一个执行,则try不在执行
        if (accountInfoDao.isExistConfirm(transId) > 0 || accountInfoDao.isExistCancel(transId) > 0) {
            log.info("bank1 try 悬挂处理,cancel或confirm 已经执行,不允许执行try,xid():"+transId);
            return ;
        }

        //扣减余额
        if (accountInfoDao.reduceAccountBalance(accountNo, amount) <= 0){
            //扣减失败
            throw new RuntimeException("bank1 try 扣减金额失败,xid():"+transId);
        }

        //插入 try 执行记录,用于幂等判断
        accountInfoDao.addTry(transId);


        //远程调用 bank2
        CommonResult transfer = bank2Service.transfer(amount);

        if(transfer.getCode() != 200){
            //调用失败
            throw new RuntimeException("远程服务调用失败,xid():"+transId);
        }

        //人为制造异常
        if (amount == 200){
            throw new RuntimeException("人为制造异常,xid():"+transId);
        }
    }

    //confirm 方法
    public void commit(String accountNo, Double amount){
        //获取全局事务 ID
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("bank1 confirm begin 开始执行了 xid():"+transId);
        //无需操作
    }

    /** cancel 方法
     * cancel幂等校验
     * cancel空回滚处理
     * 增加30元
     * @param accountNo
     * @param amount
     */
    @Transactional
    public void rollback(String accountNo, Double amount){

        //获取全局事务 ID
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("bank1 cancel begin 开始执行了 xid():"+transId);
        //幂等判断:判断local_try_log表中是否有try日志记录,如果有则不再执行
        if (accountInfoDao.isExistCancel(transId) > 0){
            log.info("bank1 cancel 幂等处理 cancel 已经执行,无需重复执行,xid():"+transId);
            return ;
        }
        //空回滚:如果 try 没有执行,cancel 不允许执行
        if (accountInfoDao.isExistTry(transId) <= 0){
            log.info("bank1 空回滚处理 try 没有执行,不允许cancel执行,xid():"+transId);
            return ;
        }
        //增加可用余额
        accountInfoDao.addAccountBalance(accountNo, amount);

        //插入cancel 执行记录
        accountInfoDao.addCancel(transId);
    }
}


controller

package com.yao.hmily.controller;

import com.yao.hmily.domain.CommonResult;
import com.yao.hmily.service.AccountInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AccountInfoController {

    @Autowired
    private AccountInfoService accountInfoService;

    //张三转账
    @GetMapping("/transfer/{amount}")
    public CommonResult transfer(@PathVariable("amount") Double amount){
        accountInfoService.updateAccountBalance("1",amount);
        return new CommonResult(200,"转账成功");
    }
}

启动类

package com.yao.hmily;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableAspectJAutoProxy
@ComponentScan(value = {"org.dromara.hmily","com.yao.hmily"})
public class Bank1Application2006 {
    public static void main(String[] args) {
        SpringApplication.run(Bank1Application2006.class,args);
    }
}

1.3.5 创建tcc-bank2-serrver

application.yml

server:
  port: 2006
spring:
  application:
    name: hmily-bank2-server
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/bank2?useSSL=false
    driver-class-name: org.gjt.mm.mysql.Driver
    type: com.alibaba.druid.pool.DruidDataSource
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848


org:
  dromara:
    hmily :
      serializer : kryo
      recoverDelayTime : 30
      retryMax : 30
      scheduledDelay : 30
      scheduledThreadMax :  10
      repositorySupport : db
      started: true
      hmilyDbConfig :
        driverClassName: com.mysql.jdbc.Driver
        url :  jdbc:mysql://localhost:3306/hmily?useUnicode=true&useSSL=false
        username : root
        password : 123456

feign:
  hystrix:
    enabled: true


mybatis:
  mapper-locations: classpath:/mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
  level:
    io:
      seata: info

config

package com.yao.hmily.config;


import org.dromara.hmily.common.config.HmilyDbConfig;
import org.dromara.hmily.core.bootstrap.HmilyTransactionBootstrap;
import org.dromara.hmily.core.service.HmilyInitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.env.Environment;


/**
 * 数据源代理
 * @author yao
 */
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class HmilyConfiguration {

    @Autowired
    private Environment env;


    @Bean
    public HmilyTransactionBootstrap hmilyTransactionBootstrap(HmilyInitService hmilyInitService){
        HmilyTransactionBootstrap hmilyTransactionBootstrap = new HmilyTransactionBootstrap(hmilyInitService);
        hmilyTransactionBootstrap.setSerializer(env.getProperty("org.dromara.hmily.serializer"));
        hmilyTransactionBootstrap.setRecoverDelayTime(Integer.parseInt(env.getProperty("org.dromara.hmily.recoverDelayTime")));
        hmilyTransactionBootstrap.setRetryMax(Integer.parseInt(env.getProperty("org.dromara.hmily.retryMax")));
        hmilyTransactionBootstrap.setScheduledDelay(Integer.parseInt(env.getProperty("org.dromara.hmily.scheduledDelay")));
        hmilyTransactionBootstrap.setScheduledThreadMax(Integer.parseInt(env.getProperty("org.dromara.hmily.scheduledThreadMax")));
        hmilyTransactionBootstrap.setRepositorySupport(env.getProperty("org.dromara.hmily.repositorySupport"));
        hmilyTransactionBootstrap.setStarted(Boolean.parseBoolean(env.getProperty("org.dromara.hmily.started")));
        HmilyDbConfig hmilyDbConfig = new HmilyDbConfig();
        hmilyDbConfig.setDriverClassName(env.getProperty("org.dromara.hmily.hmilyDbConfig.driverClassName"));
        hmilyDbConfig.setUrl(env.getProperty("org.dromara.hmily.hmilyDbConfig.url"));
        hmilyDbConfig.setUsername(env.getProperty("org.dromara.hmily.hmilyDbConfig.username"));
        hmilyDbConfig.setPassword(env.getProperty("org.dromara.hmily.hmilyDbConfig.password"));
        hmilyTransactionBootstrap.setHmilyDbConfig(hmilyDbConfig);
        return hmilyTransactionBootstrap;
    }
}

dao

package com.yao.hmily.dao;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface Bank2AccountInfoDao {

    //李四增加金额
    /**
     *
     * @param accountNo  银行卡号
     * @param amount  转账金额
     * @return
     */
    int updateAccountBalance(@Param("accountNo") String accountNo,
                             @Param("amount") Double amount);


    /**
     * 增加某分支事务try执行记录
     * @param localTradeNo 本地事务编号
     * @return
     */
    int addTry(@Param("txNo") String localTradeNo);

    /**
     * 增加某分支事务confirm执行记录
     * @param localTradeNo 本地事务编号
     * @return
     */
    int addConfirm(@Param("txNo") String localTradeNo);

    /**
     * 增加某分支事务cancel执行记录
     * @param localTradeNo 本地事务编号
     * @return
     */
    int addCancel(@Param("txNo") String localTradeNo);

    /**
     * 查询分支事务try是否已执行
     * @param localTradeNo 本地事务编号
     * @return
     */
    int isExistTry(@Param("txNo") String localTradeNo);
    /**
     * 查询分支事务confirm是否已执行
     * @param localTradeNo 本地事务编号
     * @return
     */
    int isExistConfirm(@Param("txNo") String localTradeNo);

    /**
     * 查询分支事务cancel是否已执行
     * @param localTradeNo 本地事务编号
     * @return
     */
    int isExistCancel(@Param("txNo") String localTradeNo);



}


mapper.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.yao.hmily.dao.Bank2AccountInfoDao" >

    <update id="updateAccountBalance">
        update account_info
        set
                account_balance = account_balance + #{amount}
        WHERE
                account_no = #{accountNo}
    </update>


    <insert id="addTry">
        insert into
                local_try_log
        values (#{txNo},now())
    </insert>

    <insert id="addConfirm">
        insert into
                local_confirm_log
        values (#{txNo},now());
    </insert>

    <insert id="addCancel" >
        insert into
                local_cancel_log
        values (#{txNo},now());
    </insert>
    <select id="isExistTry" resultType="java.lang.Integer">
        select
                count(1)
        from
                local_try_log
        where
                tx_no = #{txNo}
    </select>

    <select id="isExistConfirm" resultType="java.lang.Integer">
        select
                count(1)
        from
                local_confirm_log
        where
                tx_no = #{txNo}
    </select>

    <select id="isExistCancel" resultType="java.lang.Integer">
        select
                count(1)
        from
                local_cancel_log
        where
                tx_no = #{txNo}
    </select>
</mapper>


controller

package com.yao.hmily.controller;

import com.yao.hmily.domain.CommonResult;
import com.yao.hmily.service.Bank2AccountInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Bank2AccountInfoController {

    @Autowired
    private Bank2AccountInfoService bank2AccountInfoService;

    //张三转账
    @GetMapping("/transfer/{amount}")
    public CommonResult transfer(@PathVariable("amount") Double amount){
        bank2AccountInfoService.updateAccountBalance("2",amount);
        return new CommonResult(200,"转账成功");
    }
}

业务类

package com.yao.hmily.service.impl;


import com.yao.hmily.dao.Bank2AccountInfoDao;
import lombok.extern.slf4j.Slf4j;

import org.dromara.hmily.annotation.Hmily;
import org.dromara.hmily.core.concurrent.threadlocal.HmilyTransactionContextLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yao.hmily.service.Bank2AccountInfoService;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class Bank2AccountInfoServiceImpl implements Bank2AccountInfoService {


    @Autowired
    private Bank2AccountInfoDao bank2AccountInfoDao;

    /**
     * @param accountNo
     * @param amount
     * @return
     */
    @Override
    @Hmily(confirmMethod = "commit",cancelMethod = "rollback") //只要标记这个注解就是 try 方法,在注解中指定confirm,cancel 两个方法名字
    public void updateAccountBalance(String accountNo, Double amount) {

        //获取全局事务 ID
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("bank2 try begin 开始执行了 xid():"+transId);

    }

    //confirm 方法

    /**
     * confirm幂等校验
     * 正式增加30元
     * @param accountNo
     * @param amount
     */
    @Transactional
    public void commit(String accountNo, Double amount){
        //获取全局事务 ID
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("bank2 confirm begin 开始执行了 xid():"+transId);
        //幂等校验
        if (bank2AccountInfoDao.isExistConfirm(transId) > 0){
            log.info("bank2 confirm 已经执行,无需重复执行 xid():"+transId);
            return;
        }
        //增加金额
        bank2AccountInfoDao.updateAccountBalance(accountNo, amount);
        //增加一条记录
        bank2AccountInfoDao.addConfirm(transId);

    }


    public void rollback(String accountNo, Double amount){

        //获取全局事务 ID
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info("bank2 cancel begin 开始执行了 xid():"+transId);
    }

}


启动类

package com.yao.hmily;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableAspectJAutoProxy
@ComponentScan({"org.dromara.hmily","com.yao.hmily"})
public class Bank2Application2007 {
    public static void main(String[] args) {
        SpringApplication.run(Bank2Application2007.class,args);
    }
}
1.3.6 启动测试

在这里插入图片描述
在这里插入图片描述
模拟错误的情况,只能在 bank1 服务中设置错误,不能在 bank2 中设置,因为 只要 bank1 的 try 执行成功,那么 bank2 的 confirm 一定会成功,如果bank2 真的出现错误,只能由人工介入处理。

原文链接:https://blog.csdn.net/yao_wen_yu/article/details/117655599



所属网站分类: 技术文章 > 博客

作者:哦哦好吧

链接:http://www.javaheidong.com/blog/article/222299/3b786465aa03e95e7076/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

27 0
收藏该文
已收藏

评论内容:(最多支持255个字符)