seata事务无法回滚情况

这里提供两种导致seata事务无法回滚情况的解决方案,当然主要归功于前人留下的宝贵经验。

一、使用@RestControllerAdvice全局异常捕获

使用AOP手动开启全局事务并进行回滚

@Aspect
@Component
@Slf4j
public class WorkAspect {

    @Before("execution(* com.trs.slivlooncloud.service.*.*(..))")
    public void before(JoinPoint joinPoint) throws TransactionException {
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        GlobalTransaction tx = GlobalTransactionContext.getCurrentOrCreate();
        tx.begin(300000, "tran");
        log.info("**********创建分布式事务完毕 {}" , tx.getXid());
    }

    @AfterThrowing(throwing = "e", pointcut = "execution(* com.trs.slivlooncloud.service.*.*(..))")
    public void doRecoveryActions(Throwable e) throws TransactionException {
        log.info("方法执行异常:{}", e.getMessage());
        if (!StringUtils.isBlank(RootContext.getXID())) {
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
        }
    }

}

二、使用feign服务降级时回滚失效

当项目中使用了feign服务降级

feign:
  hystrix:
    enabled: true
@Component
@Slf4j
public class CreditFallBackFactory implements FallbackFactory {

    @Autowired
    private WorkAspect workAspect;

    @Override
    public CreditFeign create(Throwable throwable) {
        /**
         * 手动进行事务回滚
         */
        try {
            this.workAspect.doRecoveryActions(throwable);
        } catch (TransactionException e) {
            e.printStackTrace();
        }
        return new CreditFeign() {
            @Override
            public void increaseAmount(Bonus bonus) {
                log.info("服务降级 {}", throwable);
            }
        };
    }
}

 

你可能感兴趣的:(seata事务无法回滚情况)