springcloud分布式事务处理方案

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangxing52077/article/details/81587988

1.场景还原

     笔者在公司最近的一个项目采用springcloud框架搭建微服务架构,这势必会引发分布式事务处理的思考,目前处理分布式主流方案tcc及消息的最终一致性;今天笔者集成github上较为流行的tx-lcn分布式处理框架,它是基于redis的一种补偿型处理方案

2.实现方案

①先截图,下载该框架

从github上的starts数量来看,目前还是较多开发者采用了这种方案的,而且作者维护迭代也很及时

②将tx-manager微服务单独拎出来,集成在自己的项目中

将tx-manager中application.properties中的配置改成自己的项目配置

③然后涉及分布式的微服务中添加如下依赖

<!--分布式事物-->
<dependency>
   <groupId>com.codingapi</groupId>
   <artifactId>transaction-springcloud</artifactId>
   <version>${lcn.last.version}</version>
   <exclusions>
      <exclusion>
         <groupId>org.slf4j</groupId>
         <artifactId>*</artifactId>
      </exclusion>
   </exclusions>
</dependency>

<dependency>
   <groupId>com.codingapi</groupId>
   <artifactId>tx-plugins-db</artifactId>
   <version>${lcn.last.version}</version>
   <exclusions>
      <exclusion>
         <groupId>org.slf4j</groupId>
         <artifactId>*</artifactId>
      </exclusion>
   </exclusions>
</dependency>

④下载tx-demo,参考链接:https://github.com/codingapi/springcloud-lcn-demo

将其中的两个实现类复制到自己工程的service中

⑤开启tx-manager,在各个微服务application.yml配置tx-manager地址

# 分布式事物
tm:
  manager:
    url: http://localhost:8899/tx/manager/

3.应用步骤

①分布式事务起始服务方

@Transactional
@TxTransaction(isStart = true)
public int addAcount(String logId){
   int i = yiViUserAccountMapper.increaseAccount("100","71d8beff-9e70-11e7-9a60-00163e0a3457");

   int n =  paymentDispatchFeignClient.test(logId); //调用失败

   if(n == 0){
       throw new RuntimeException("服务调用失败");
   }
    return i + n;
}

②被调用服务方

@Override
@Transactional
@TxTransaction
public int test(String logId) throws YiViException {
    int i = yiViDispatchOrderStatusLogMapper.deleteByPrimaryKey(logId);
    return i;
}

如此便可,好了我是张星,欢迎加入博主技术交流群,群号:526601468

猜你喜欢

转载自blog.csdn.net/zhangxing52077/article/details/81587988