文章目录
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的注意事项:
- 客户端在配置上tx-lcn.client.manager-address地址后,启动时必须要全部可访问客户端才能正常启动。
- 当tx-lcn.client.manager-address中的服务存在不可用时,客户端会重试链接11次,超过次数以后将不在重试,重试链接的间隔时间为15秒,当所有的TxManager都不可访问则会导致所有的分布式事务请求都失败回滚。
- 当增加一个新的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
