分布式事务-TX-LCN 的lcn模式和tcc模式

分布式事务-TX-LCN 的lcn模式和tcc模式文章目录 1 TX LCN 介绍 1 TX LCN 概念介绍 2 TX LCN 原理 2 TX LCN 中的 lcn 模式开发 1 准备 TM0 准备 tm 的数据库 1 POM 配置 2 更改配置 3 注解 2 准备其他的服务 TC1 pom2 配置 3 注解 4 使用 3 TX LCN 中的 tcc 模式开发 1 准备 TM0 准备 tm 的数据库 1 POM 配置 2 更改配置 3 注解 2 准备其他的服务 TC1 pom2 配置 3 注解 4 使用 4 TM 集群 1 集群概念 2 集群配置 1 TX LCN 介绍 1 TX LCN 概念介绍 LCN 框架在 2017 年 6 月份发布第

1:TX-LCN 介绍

1:TX-LCN概念介绍

  • 锁定事务单元(lock)
  • 确认事务模块状态(confirm)
  • 通知事务(notify)

5.0以后由于框架兼容了LCN、TCC、TXC三种事务模式,为了避免区分LCN模式,特此将LCN分布式事务改名为TX-LCN分布式事务框架。

协调者称之为TxManager , 参与者称之为 TxClient

lcn官网:https://www.codingapi.com/docs/txlcn-setting-manager/(如果进不去,多刷新几次)

TX-LCN 主要有两个模块,Tx-Client(TC) Tx-Manager™. TC作为微服务下的依赖,TM是独立的服务。

2:TX-LCN原理

2:TX-LCN 中的lcn模式开发

1:准备TM

0:准备tm的数据库

DROP TABLE IF EXISTS `t_tx_exception`; CREATE TABLE `t_tx_exception` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `group_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `unit_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `mod_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `transaction_state` tinyint(4) NULL DEFAULT NULL, `registrar` tinyint(4) NULL DEFAULT NULL COMMENT '-1 未知 0 Manager 通知事务失败, 1 client询问事务状态失败2 事务发起方关闭事务组失败', `ex_state` tinyint(4) NULL DEFAULT NULL COMMENT '0 待处理 1已处理', `create_time` datetime(0) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 967 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1; 

注:也可以通过下载

1:POM配置

 
    <dependency> <groupId>com.codingapi.txlcn 
     groupId> <artifactId>txlcn-tm 
      artifactId> <version>5.0.2.RELEASE 
       version>  
        dependency> <dependency> <groupId>com.codingapi.txlcn 
         groupId> <artifactId>txlcn-tc 
          artifactId> <version>5.0.2.RELEASE 
           version>  
            dependency> <dependency> <groupId>com.codingapi.txlcn 
             groupId> <artifactId>txlcn-txmsg-netty 
              artifactId> <version>5.0.2.RELEASE 
               version>  
                dependency>  
                

2:更改配置

# TM事务管理器的服务端WEB访问端口。提供一个可视化的界面。端口自定义。 server.port=7970 # TM事务管理器,需要访问数据库,实现分布式事务状态记录。 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/tx-manager?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=root # TM事务管理器,是依赖Redis使用分布式事务协调的。尤其是TCC和TXC两种事务模型。 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.database=0 # 为spring应用起名。 spring.application.name=tx-lcn-transaction-manager # TM事务管理器,提供的WEB管理平台的登录密码。无用户名。 默认是codingapi tx-lcn.manager.admin-key=root # 日志。如果需要TM记录日志。则开启,赋值为true,并提供后续的配置。 tx-lcn.logger.enabled=true # 为日志功能,提供数据库连接。和之前配置的分布式事务管理依赖使用的数据源不同。 tx-lcn.logger.driver-class-name=com.mysql.cj.jdbc.Driver tx-lcn.logger.jdbc-url=jdbc:mysql://localhost:3306/tx-manager?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai tx-lcn.logger.username=root tx-lcn.logger.password=root 

3:注解

在主类上使用@EnableDistributedTransaction

SpringBootApplication @EnableDistributedTransaction public class DemoAApplication { 
    public static void main(String[] args) { 
    SpringApplication.run(DemoDubboClientApplication.class, args); } } 

2:准备其他的服务TC

1:pom

  
    <dependency> <groupId>org.springframework.boot 
     groupId> <artifactId>spring-boot-starter-data-redis 
      artifactId>  
       dependency>  
       <dependency> <groupId>com.codingapi.txlcn 
        groupId> <artifactId>txlcn-tc 
         artifactId> <version>5.0.2.RELEASE 
          version>  
           dependency> <dependency> <groupId>com.codingapi.txlcn 
            groupId> <artifactId>txlcn-txmsg-netty 
             artifactId> <version>5.0.2.RELEASE 
              version>  
               dependency> 

2:配置

 server: port: 1001 #应用名称及验证账号 spring: application: name: lcn-order datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/lcn-order?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai username: root password: root dbcp2: initial-size: 5 min-idle: 5 max-total: 5 max-wait-millis: 200 validation-query: SELECT 1 test-while-idle: true test-on-borrow: false test-on-return: false mybatis: mapper-locations: - classpath:mapper/*.xml eureka: client: service-url: defaultZone: http://localhost:7900/eureka/ # tm配置----主要就是这里 tx-lcn: client: manager-address: 127.0.0.1:8071 logging: level: root: info 

3:注解

在主类上使用@EnableDistributedTransaction

package com.mashibing.lcnorder; import com.codingapi.txlcn.tc.config.EnableDistributedTransaction; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableDistributedTransaction public class LcnOrderApplication { 
    public static void main(String[] args) { 
    SpringApplication.run(LcnOrderApplication.class, args); } @Bean @LoadBalanced public RestTemplate restTemplate(){ 
    return new RestTemplate(); } } 

4:使用

1:服务A

package com.mashibing.lcnorder.controller; import com.codingapi.txlcn.tc.annotation.LcnTransaction; import com.mashibing.lcnorder.dao.TblOrderDao; import com.mashibing.lcnorder.entity.TblOrder; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class OrderController { 
    @Autowired private TblOrderDao tblOrderDao; @Autowired private RestTemplate restTemplate; @GetMapping("/test") public String test(){ 
    return "hello world"; } @PostMapping("/add-order") @Transactional(rollbackFor = Exception.class) //本地事务管理器 @LcnTransaction //lcn事务管理器 public String add(@RequestBody TblOrder bean){ 
    JSONObject date = new JSONObject(); date.put("payName",bean.getOrderName()+"pay"); //调用B服务 restTemplate.postForEntity("http://lcn-pay/add-pay",date,String.class); int i = 1/0; tblOrderDao.insert(bean); return "新增订单成功"; } } 

2:服务B

package com.mashibing.lcnpay.controller; import com.codingapi.txlcn.tc.annotation.LcnTransaction; import com.mashibing.lcnpay.dao.TblPayDao; import com.mashibing.lcnpay.entity.TblPay; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class PayController { 
    @Autowired private TblPayDao tblPayDao; @PostMapping("/add-pay") @Transactional(rollbackFor = Exception.class) @LcnTransaction public String addPay(@RequestBody TblPay bean){ 
    tblPayDao.insert(bean); // int i = 1/0; return "新增支付成功"; } } 

3:TX-LCN 中的tcc模式开发

1:准备TM

0:准备tm的数据库

DROP TABLE IF EXISTS `t_tx_exception`; CREATE TABLE `t_tx_exception` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `group_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `unit_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `mod_id` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `transaction_state` tinyint(4) NULL DEFAULT NULL, `registrar` tinyint(4) NULL DEFAULT NULL COMMENT '-1 未知 0 Manager 通知事务失败, 1 client询问事务状态失败2 事务发起方关闭事务组失败', `ex_state` tinyint(4) NULL DEFAULT NULL COMMENT '0 待处理 1已处理', `create_time` datetime(0) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 967 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1; 

注:也可以通过下载

1:POM配置

 
    <dependency> <groupId>com.codingapi.txlcn 
     groupId> <artifactId>txlcn-tm 
      artifactId> <version>5.0.2.RELEASE 
       version>  
        dependency> <dependency> <groupId>com.codingapi.txlcn 
         groupId> <artifactId>txlcn-tc 
          artifactId> <version>5.0.2.RELEASE 
           version>  
            dependency> <dependency> <groupId>com.codingapi.txlcn 
             groupId> <artifactId>txlcn-txmsg-netty 
              artifactId> <version>5.0.2.RELEASE 
               version>  
                dependency>  
                

2:更改配置

# TM事务管理器的服务端WEB访问端口。提供一个可视化的界面。端口自定义。 server.port=7970 # TM事务管理器,需要访问数据库,实现分布式事务状态记录。 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/tx-manager?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai spring.datasource.username=root spring.datasource.password=root # TM事务管理器,是依赖Redis使用分布式事务协调的。尤其是TCC和TXC两种事务模型。 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.database=0 # 为spring应用起名。 spring.application.name=tx-lcn-transaction-manager # TM事务管理器,提供的WEB管理平台的登录密码。无用户名。 默认是codingapi tx-lcn.manager.admin-key=root # 日志。如果需要TM记录日志。则开启,赋值为true,并提供后续的配置。 tx-lcn.logger.enabled=true # 为日志功能,提供数据库连接。和之前配置的分布式事务管理依赖使用的数据源不同。 tx-lcn.logger.driver-class-name=com.mysql.cj.jdbc.Driver tx-lcn.logger.jdbc-url=jdbc:mysql://localhost:3306/tx-manager?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai tx-lcn.logger.username=root tx-lcn.logger.password=root 

3:注解

在主类上使用@EnableDistributedTransaction

SpringBootApplication @EnableDistributedTransaction public class DemoAApplication { 
    public static void main(String[] args) { 
    SpringApplication.run(DemoDubboClientApplication.class, args); } } 

2:准备其他的服务TC

1:pom

  
    <dependency> <groupId>org.springframework.boot 
     groupId> <artifactId>spring-boot-starter-data-redis 
      artifactId>  
       dependency>  
       <dependency> <groupId>com.codingapi.txlcn 
        groupId> <artifactId>txlcn-tc 
         artifactId> <version>5.0.2.RELEASE 
          version>  
           dependency> <dependency> <groupId>com.codingapi.txlcn 
            groupId> <artifactId>txlcn-txmsg-netty 
             artifactId> <version>5.0.2.RELEASE 
              version>  
               dependency> 

2:配置

 server: port: 1001 #应用名称及验证账号 spring: application: name: lcn-order datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/lcn-order?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai username: root password: root dbcp2: initial-size: 5 min-idle: 5 max-total: 5 max-wait-millis: 200 validation-query: SELECT 1 test-while-idle: true test-on-borrow: false test-on-return: false mybatis: mapper-locations: - classpath:mapper/*.xml eureka: client: service-url: defaultZone: http://localhost:7900/eureka/ # tm配置----主要就是这里 tx-lcn: client: manager-address: 127.0.0.1:8071 logging: level: root: info 

3:注解

在主类上使用@EnableDistributedTransaction

package com.mashibing.lcnorder; import com.codingapi.txlcn.tc.config.EnableDistributedTransaction; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication @EnableDistributedTransaction public class LcnOrderApplication { 
    public static void main(String[] args) { 
    SpringApplication.run(LcnOrderApplication.class, args); } @Bean @LoadBalanced public RestTemplate restTemplate(){ 
    return new RestTemplate(); } } 

4:使用

1:服务A

package com.mashibing.lcnorder.controller; import com.codingapi.txlcn.tc.annotation.LcnTransaction; import com.codingapi.txlcn.tc.annotation.TccTransaction; import com.mashibing.lcnorder.dao.TblOrderDao; import com.mashibing.lcnorder.entity.TblOrder; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.Map; import java.util.UUID; @RestController public class OrderTccController { 
    @Autowired private TblOrderDao tblOrderDao; @Autowired private RestTemplate restTemplate; @PostMapping("/add-order-tcc") @Transactional(rollbackFor = Exception.class) @TccTransaction public String add(@RequestBody TblOrder bean){ 
    System.out.println("add 正常线程名:"+Thread.currentThread().getName()); JSONObject date = new JSONObject(); date.put("payName",bean.getOrderName()+"pay"); restTemplate.postForEntity("http://lcn-pay/add-pay-tcc",date,String.class); tblOrderDao.insert(bean); Integer id = bean.getId(); // maps.put("a",id); ids.put("a",id); // int i = 1/0; return "新增订单成功"; } public String confirmAdd(TblOrder bean){ 
    System.out.println("add 确认线程名:"+Thread.currentThread().getName()); System.out.println("order confirm "); return "新增订单成功"; } // private static Map 
   
     maps = new HashMap<>(); 
    private static Map<String,Integer> ids = new HashMap<>(); public String cancelAdd(TblOrder bean){ 
    System.out.println("add 取消线程名:"+Thread.currentThread().getName()); // Integer a = maps.get("a"); Integer a = ids.get("a"); System.out.println("a:"+a); tblOrderDao.deleteByPrimaryKey(a); System.out.println("order cancel "); return "新增订单成功"; } } 

2:服务B

package com.mashibing.lcnpay.controller; import com.codingapi.txlcn.tc.annotation.LcnTransaction; import com.codingapi.txlcn.tc.annotation.TccTransaction; import com.mashibing.lcnpay.dao.TblPayDao; import com.mashibing.lcnpay.entity.TblPay; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController public class PayTccController { 
    @Autowired private TblPayDao tblPayDao; @PostMapping("/add-pay-tcc") @Transactional(rollbackFor = Exception.class) @TccTransaction public String addPay(@RequestBody TblPay bean){ 
    tblPayDao.insert(bean); Integer id = bean.getId(); maps.put("a",id); // int i = 1/0; return "新增支付成功"; } public String confirmAddPay(TblPay bean){ 
    System.out.println("pay confirm"); return "新增支付成功"; } private static Map<String,Integer> maps = new HashMap<>(); / * 逆sql * @param bean * @return */ public String cancelAddPay(TblPay bean){ 
    Integer a = maps.get("a"); System.out.println("a:"+a); System.out.println("pay cancel"); tblPayDao.deleteByPrimaryKey(a); return "取消支付成功"; } } 

4:TM集群

1:集群概念

TxManager集群比较简单,只需要控制TxManager下的db资源相同(mysql 、redis)部署多份即可,注意TxManager负载均衡5.0版本与之前版本机制不同。

目前TX-LCN的负载机制仅提供了随机机制。

关于tx-lcn.client.manager-address的注意事项:

  1. 客户端在配置上tx-lcn.client.manager-address地址后,启动时必须要全部可访问客户端才能正常启动。
  2. 当tx-lcn.client.manager-address中的服务存在不可用时,客户端会重试链接11次,超过次数以后将不在重试,重试链接的间隔时间为15秒,当所有的TxManager都不可访问则会导致所有的分布式事务请求都失败回滚。
  3. 当增加一个新的TxManager的集群模块时不需要添加到tx-lcn.client.manager-address下,TxManager也会广播到所有的TxManager端再通知所有链接中的TxClient端新的TxManager加入。

2:集群配置

使用步骤:

首选需要启动多个TxManager服务。

在客户端配置TxManager服务地址。

tx-lcn.client.manager-address=127.0.0.1:8070,127.0.0.1:8072

原理介绍:

当有事务请求客户端时事务发起端会随机选择一个可用TxManager作为事务控制方,然后告知其参与模块都与该模块通讯。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/227773.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月16日 下午8:34
下一篇 2026年3月16日 下午8:34


相关推荐

  • IntelliJ IDEA创建maven web项目(IDEA新手适用)

    IntelliJ IDEA创建maven web项目(IDEA新手适用)PS:从eclipse刚转到IDEA,对于这个陌生的工具我表示无言,但听说很好用,也就试试,结果我几乎花了一晚上的时间才搭起来mavenweb项目,觉得在此给各位一个搭建mavenweb项目的教程,指出我踩过的各种坑!步骤一:首先先创建一个project,在这里就是创建一个maven的工作空间步骤二:按照下面的步骤操作就可以了,最后next首先,选择左边的maven然后在右…

    2022年6月26日
    58
  • php前端开发工程师简历,web前端工程师简历自我评价范文

    php前端开发工程师简历,web前端工程师简历自我评价范文web 前端工程师简历自我评价范文一有 3 年以上经验 积极向上 有良好的人际沟通能力 良好的工作协调能力 踏实肯干的工作精神 不断学习新技术 对知识有强烈的求知欲 良好的前端编程能力和编程习惯 致力于代码的整体结构规范及优化 web 前端工程师简历自我评价范文二具备前端工程师所要求的各种语言 主流框架以及软件技能 有两年的前端开发经验 熟练使用 HTML5 CSS3 等前台语言 并对 PHP thinkPHP

    2026年3月18日
    2
  • java绝对值API「建议收藏」

    直接使用Math.abs(x);

    2022年4月6日
    46
  • docker 修改容器时间_docker容器时间与宿主机不一致

    docker 修改容器时间_docker容器时间与宿主机不一致前言用docker搭建的Jenkins环境时间显示和我们本地时间相差8个小时,需修改容器内部的系统时间查看时间查看系统时间date-R进入docker容器内部,查看容器时间dockere

    2022年8月6日
    6
  • kotlin的Map集合

    kotlin的Map集合kotlin的Map集合只读Map可变的MapmutableMapOfkotlin的Map分为:只读Map。可变的MutableMap(MutableMap、HashMap、LinkedHashMap)。只读Map意味着我们创建出来的map是不可变的,即我们只能使用无法改变我们map中的数据,我们只能获取集合中的数据而无法对集合中的数据进行新增和修改。/***…

    2022年5月18日
    37
  • 如何快速成长为不可或缺的技术人才?

    如何快速成长为不可或缺的技术人才?

    2021年10月22日
    43

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号