美文网首页
微服务集成tx-lcn分布式事务指南

微服务集成tx-lcn分布式事务指南

作者: 柠檬冰块 | 来源:发表于2020-11-16 21:26 被阅读0次

微服务集成tx-lcn分布式事务指南

添加tx-lcn依赖

在xxx-service项目的pom文件中,添加以下两个依赖,

不需要写版本号,会自动继承父项目。若没用从父项目继承版本号,则删除本地maven仓库的vip.isass目录,再试。

<dependency>

    <groupId>com.codingapi.txlcn</groupId>

    <artifactId>txlcn-tc</artifactId>

</dependency>

<dependency>

    <groupId>com.codingapi.txlcn</groupId>

    <artifactId>txlcn-txmsg-netty</artifactId>

</dependency>

程序入口类添加注解

在 xxxApp 主程序入口类添加注解 @EnableDistributedTransaction

@ComponentScan("vip.isass", "com.sancaijia")

@SpringCloudApplication

@EnableDistributedTransaction

public class AuthApp {

        public static void main(String[] args) throws Exception {

            SpringApplication.run(AuthApp.class, args);

        }

}

事务方法添加注解

在需要用到分布式事务的方法上,添加两个注解@LcnTransaction, @Transactional(rollbackFor = Exception.class)。注解@LcnTransaction必须在前面

@LcnTransaction

@Transactional(rollbackFor = Exception.class)

public void test() {

    baseFeignClient.test().exceptionIfUnSuccess();

    v1StaffService.add(new Staff().randomEntity());

}

添加TxManager配置

nacos 配置中心已添加 TxManager 配置, 开发人员无需关注

跨微服务调用的异常抛出

B 服务有 bClient.foo(), A 服务调用了 bClient.foo()。如果 A 服务希望 B 服务的 foo() 报错时,A 不再往下执行代码,则需要把 B 服务返回的异常结果抛出。抛出示例:

如果 B 服务的 foo() 报错, A 服务没有抛出 B 服务的异常,则视为 A 不关心 B的 foo() 是否执行成功, 即 A 会往下执行代码,A 的事务会被提交。(B 因为报错了,B 的事务会回滚)

    bClient.foo().exceptionIfUnSuccess();

    或者

    bClient.foo().dataIfSuccessOrException();

    或者自行判断 foo() 的返回值,决定是否抛出异常

tx-lcn官网

https://www.txlcn.org/zh-cn/index.html

相关文章

网友评论

      本文标题:微服务集成tx-lcn分布式事务指南

      本文链接:https://www.haomeiwen.com/subject/jvzzbktx.html