一、 什么是分布式事务
分布式事务是指事务的参与者、支持事务的服务器、资源服务器以及事务管理器分别位 于不同的分布式系统的不同节点之上。 举个例子: 电商系统中的订单系统与库存系统
图中包含了库存和订单两个独立的微服务,每个微服务维护了自己的数据库。在交易系 统的业务逻辑中,一个商品在下单之前需要先调用库存服务,进行扣除库存,再调用订单服务,创建订单记录。
正常情况下,两个数据库各自更新成功,两边数据维持着一致性。 如果在非正常情况下,有可能库存的扣减完成了,随后的订单记录却因为某些原因插入 失败。或者是订单创建成功了,但是库存扣除商品的数据量失败了,这个时候,两边数据就 失去了应有的一致性
这时候就需要保证事务的一致性了,单数据源的用单机事务来保证。多数据源就需要依 赖分布式事务来处理。
二、什么是 LCN 框架
1、LCN 框架的由来 LCN 并不生产事务,LCN 只是本地事务的协调工。 在设计框架之初的 1.0~2.0 的版本时,框架设计的步骤是如下的,各取其首字母得来 的 LCN 命名。 锁定事务单元(lock)、确认事务模块状态(confirm)、通知事务(notify)
2、LCN 框架相关资料
tx-lcn 官方地址:https://www.txlcn.org/
tx-lcn Github 地址:https://github.com/codingapi/tx-lcn
tx-lcn 服务下载地址:https://pan.baidu.com/s/1cLKAeE#list/path=%2F
tx-lcn 服务源码地址:https://github.com/codingapi/tx-lcn/tree/master/tx-manager
三、 LCN 框架原理及执行步骤
1、LCN 的执行原理 LCN 原理
在上图中,微服务 A,微服务 B,TxManager 事务协调器,都需要去 Eureka 中注册服务。Eureka 是用于 TxManager 与其他服务之间的相互服务发现。redis 是用于存放我们事务组的信息以及补偿的信息。然后微服务 A 与微服务 B 他们都需要去配置上我们 TxClient 的 包架构(代码的包架构);来支持我们的 LCN 框架,以及他们的数据库。
2、 LCN 执行步骤
2.1创建事务组:
事务组是指的我们在整个事务过程中把各个节点(微服务)单元的事务信息存储在一 个固定单元里。但这个信息并不是代表是事务信息,而是只是作为一个模块的标示信息。 创建事务组是指在事务发起方开始执行业务代码之前先调用 TxManager 创建事务组 对象,然后拿到事务标示 GroupId 的过程。
2.2、添加事务组:
添加事务组是指参与方在执行完业务方法以后,将该模块的事务信息添加通知给 TxManager 的操作。
2.3、关闭事务组:
是指在发起方执行完业务代码以后,将发起方执行结果状态通知给 TxManager 的动 作。当执行完关闭事务组的方法以后,TxManager 将根据事务组信息来通知相应的参与模 块提交或回滚事务。
2.4、业务执行流程图
三、 什么是 LCN 的事务协调机制
如图:假设服务已经执行到关闭事务组的过程,那么接下来作为一个模块执行通知给 TxManager,然后告诉他本次事务已经完成。那么如图中 Txmanager 下一个动作就是通过事务组的 id,获取到本次事务组的事务信息;然后查看一下对应有那几个模块参与,然后如果 是有 A/B/C 三个模块;那么对应的对三个模块做通知、提交、回滚。
1. 那么提交的时候是提交给谁呢?
提交给了我们的 TxClient 模块。然后 TxCliient 模块下有一个连接池,就是框架自定义的一个连接池(如图 DB 连接池);这个连接池其实就是在没有通知事务之前一直占有着 这次事务的连接资源,就是没有释放。但是他在切面里面执行了 close 方法。在执行 close 的时候。如果需要(TxManager)分布式事务框架的连接。他被叫做“假关闭”,也就是没有关闭,只是在执行了一次关闭方法。实际的资源是没有释放的。这个资源是掌握在 LCN 的连接池里的。
2. 然后当 TxManager 通知提交或事务回滚的时候呢?
TxManager 会通知我们的 TxClient 端。然后 TxClient 会去执行相应的提交或回滚。提交或回滚之后再去关闭连接。这就是 LCN 的事务协调机制。说白了就是代理 DataSource 的机制;相当于是拦截了一下连接池,控制了连接池的事务提交。
四、 什么是 LCN 的事务补偿机制
1、什么是补偿事务机制?
LCN 的补偿事务原理是模拟上次失败事务的请求,然后传递给 TxClient 模块然后再次执行该次请求事务。 简单的说:lcn 事务补偿是指在服务挂机和网络抖动情况下 txManager 无法通知事务单元时。(通知不到也就两种原因服务挂了和网络出问题)在这种情况下 TxManager 会做一个标示;然后返回给发起方。告诉他本次事务有存在没有通知到的情况。那么如果是接收到这个信息之后呢,发起方就会做一个标示,标示本次事务是需要补偿事务的。这就是事务补偿机制。
2、为什么需要事务补偿?
事务补偿是指在执行某个业务方法时,本应该执行成功的操作却因为服务器挂机或者网络抖动等问题导致事务没有正常提交,此种场景就需要通过补偿来完成事务,从而达到事务的一致性。
3、补偿机制的触发条件?
当执行关闭事务组步骤时,若发起方接受到失败的状态后将会把该次事务识别为待补偿事务,然后发起方将该次事务数据异步通知给 TxManager。TxManager 接受到补偿事务以后先通知补偿回调地址,然后再根据是否开启自动补偿事务状态来补偿或保存该次切面事务数据。
五、模拟场景演示
若存在事务发起方、参与方A、参与方B。调用关系图如下
那么他们正常执行业务的时序图为:
若参与方B出现异常,那么他们的业务时序图为:
若他们的调用关系是这样的情况
六、 LCN 分布式事务框架应用
官方文档 https:// txlcn.org/zh-cn/docs/pr eface.html
1. LCN 应用案例设计(springcloud整合分布式事务框架TX-LCN)
搭建springcloud项目
开发环境:jdk1.8、idea2019.3、maven3.6.1 、mysql、redis
请先配置好开发环境
创建maven父工程,命名为 :spring-cloud-txlcn
创建成功,目录结构如下:
直接删掉src目录,因为是父子工程,该src没有什么作用,删掉后如下:
创建子工程,注册中心:命名为:txlcn-registry
创建成功后目录结构如下:
创建子工程 txlcn-base-a txlcn-base-b txlcn-tm
按照创建注册中心的方式创建如上几个子工程
创建成功的目录结构如下:
父工程配置
找到父工程下的pom,配置需要的依赖及其指定版本
依赖如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.it</groupId>
<artifactId>spring-cloud-txlcn</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>txlcn-registry</module>
<module>txlcn-base-a</module>
<module>txlcn-base-b</module>
<module>txlcn-tm</module>
</modules>
<!--springboot依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/>
</parent>
<!--jdk及其版本指定-->
<properties>
<!-- project -setting -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR1</spring-cloud.version>
<codingapi.txlcn.version>5.0.2.RELEASE</codingapi.txlcn.version>
<mapper.starter.version>2.1.5</mapper.starter.version>
<mysql.version>5.1.48</mysql.version>
<pagehelper.starter.version>1.2.13</pagehelper.starter.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>${mapper.starter.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--txlcn 依赖-->
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-tc</artifactId>
<version>${codingapi.txlcn.version}</version>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-txmsg-netty</artifactId>
<version>${codingapi.txlcn.version}</version>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-tm</artifactId>
<version>${codingapi.txlcn.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
注册中心配置与启动
进入到子工程 txlcn-registry 中,为其pom添加依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-txlcn</artifactId>
<groupId>com.it</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.it</groupId>
<artifactId>txlcn-registry</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
</project>
在其src/main/resources下创建application.yml配置文件:
server:
port: 8500
spring:
application:
name: txlcn-registry
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8500/eureka
fetch-registry: false #不拉取服务列表
register-with-eureka: false #不注册自己
在src/main/java 下创建启动类 RegistrtyApplication.java ,包目录为 com.it
内容如下:
package com.it;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* @author :3hzqy
* @date :Created in 2022/3/3 16:04
* @Description:
*/
@SpringBootApplication
@EnableEurekaServer
public class RegistrtyApplication {
public static void main(String[] args){
SpringApplication.run(RegistrtyApplication.class);
}
}
启动,访问测试:浏览器访问 http://localhost:8000
TXLCN分布式事务管理器配置与启动
mysql数据库执行sql语句:
CREATE DATABASE `tx-manager`;
USE `tx-manager`;
CREATE TABLE `t_tx_exception` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`group_id` varchar(64) 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(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`transaction_state` tinyint(4) NULL DEFAULT NULL,
`registrar` tinyint(4) NULL DEFAULT NULL,
`remark` varchar(4096) NULL DEFAULT NULL,
`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 = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
确认本地redis已开启
进入子工程 txlcn-tm 中,为其pom添加依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-txlcn</artifactId>
<groupId>com.it</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.it</groupId>
<artifactId>txlcn-tm</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-tm</artifactId>
</dependency>
</dependencies>
</project>
在其src/main/resources添加配置文件application.properties,配置如下:
##################
# 这个是启动本服务的配置文件
# https://txlcn.org/zh-cn/docs/setting/manager.html 查看所有的个性化配置
#################
# 服务名称及其端口
spring.application.name=TransactionManager
server.port=7970
# 数据库配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/tx-manager?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=update
# 开启日志,默认为false
tx-lcn.logger.enabled=true
tx-lcn.logger.driver-class-name=${spring.datasource.driver-class-name}
tx-lcn.logger.jdbc-url=${spring.datasource.url}
tx-lcn.logger.username=${spring.datasource.username}
tx-lcn.logger.password=${spring.datasource.password}
# TM后台登陆密码,默认值为codingapi
tx-lcn.manager.admin-key=codingapi
# redis 的设置信息
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=
在其src/main/java下创建启动类,TxlcnTmApplication.java ,包目录为 com.it
其内容为:
package com.it;
import com.codingapi.txlcn.tm.config.EnableTransactionManagerServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author :3hzqy
* @date :Created in 2022/3/3 16:27
* @Description:
*/
@SpringBootApplication
@EnableTransactionManagerServer
public class TxlcnTmApplication {
public static void main(String[] args) {
SpringApplication.run(TxlcnTmApplication.class,args);
}
}
启动测试,浏览器输入:http://localhost:7970 默认密码:codingapi
服务txlcn-base-a的配置与启动
删掉txlcn-base-a的src目录,在txlcn-base-a下创子工程,txlcn-base-a-interface 、 txlcn-base-a-service
为txlcn-base-a-service下的pom引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>txlcn-base-a</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>txlcn-base-a-service</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-tc</artifactId>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-txmsg-netty</artifactId>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>txlcn-base-a-interface</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>txlcn-base-b-interface</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
在其src/main/resources下创建application.yml配置文件
server:
port: 8001
spring:
application:
name: txlcn-base-a-service
datasource:
url: jdbc:mysql://localhost:3306/test_data
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
main:
allow-bean-definition-overriding: true #开启覆盖相同的feign名称
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8500/eureka
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
registry-fetch-interval-seconds: 5
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
创建启动类 TxlcnBaseAServiceApplication.java,包路径为com.it
package com.it;
import com.codingapi.txlcn.tc.config.EnableDistributedTransaction;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import tk.mybatis.spring.annotation.MapperScan;
/**
* @author :3hzqy
* @date :Created in 2022/3/3 16:35
* @Description:
*/
@SpringBootApplication
@EnableFeignClients //springcloud feign调用
@EnableDiscoveryClient //springcloud服务发现
@MapperScan("com.it.mapper") //扫描mapper文件所在包
@EnableDistributedTransaction //开启LcnTransaction分布式事务框架
public class TxlcnBaseAServiceApplication {
public static void main(String[] args) {
SpringApplication.run(TxlcnBaseAServiceApplication.class, args);
}
}
创建相关包路径,mapper、service、controller、client
如下:
配置 txlcn-base-a-interface ,pom添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>txlcn-base-b</artifactId>
<groupId>com.it</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.it</groupId>
<artifactId>txlcn-base-b-interface</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-core</artifactId>
<version>1.1.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
</dependencies>
</project>
创建 pojo 、api 包
服务txlcn-base-b-service的配置与启动
与txlcn-base-a-service相同,不同的就是application.yml配置:
server:
port: 8002
spring:
application:
name: txlcn-base-a-service
datasource:
url: jdbc:mysql://localhost:3306/test_data
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
main:
allow-bean-definition-overriding: true #开启覆盖相同的feign名称
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8500/eureka
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
registry-fetch-interval-seconds: 5
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
还有 txlcn-base-b-service 的pom依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>txlcn-base-b</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>txlcn-base-b-service</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-tc</artifactId>
</dependency>
<dependency>
<groupId>com.codingapi.txlcn</groupId>
<artifactId>txlcn-txmsg-netty</artifactId>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>txlcn-base-b-interface</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
以及启动类:
@SpringBootApplication
@EnableFeignClients //springcloud feign调用
@EnableDiscoveryClient //springcloud服务发现
@MapperScan("com.it.mapper") //扫描mapper文件所在包
@EnableDistributedTransaction //开启LcnTransaction分布式事务框架
public class TxlcnBaseBServiceApplication {
public static void main(String[] args) {
SpringApplication.run(TxlcnBaseBServiceApplication.class,args);
}
}
txlcn-base-b-interface与txlcn-base-b-interface一样完整如下:
分布式案例实现,服务A添加用户,同时调用服务B添加用户,A在调用B之后抛出异常
创建数据库及其表,配置的数据库是 test_data
CREATE DATABASE `test_data`;
USE `test_data`;
CREATE TABLE `tb_test` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
服务txlcn-base-b中创建实体
@Data
@Table(name = "tb_test")
public class TestPO {
@Id
@KeySql(useGeneratedKeys = true)
private Long id;
private String name;
}
创建mapper,
BaseMapper
@RegisterMapper
public interface BaseMapper<T, PK> extends Mapper<T>, IdListMapper<T, PK>, InsertListMapper<T> {
}
TestMapper
public interface TestMapper extends BaseMapper<TestPO,Long> {
}
创建service接口及其实现类
TestService
public interface TestService {
void insert(TestPO po);
}
TestServiceImpl
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
public void insert(TestPO po) {
testMapper.insert(po);
}
}
创建controller
启动 txlcn-base-b-service 测试,访问:http://localhost:8002/test/insert?name=piao
查看数据库 :
则 txlcn-base-a 也如 txlcn-base-b 相同配置,并测试!
浏览器访问:http://localhost:8001/test/insert?name=xu
实现A调用B
txlcn-base-b api的包下添加访问接口
public interface TestApi {
@GetMapping("/test/insert")
String insert(@RequestParam("name") String name);
}
txlcn-base-a 继承 txlcn-base-b 的接口,在client包下创建接口继承txlcn-base-b的api接口,并使用fegin注解标注服务id
导入txlcn-base-b-interface的依赖
<dependency>
<groupId>org.example</groupId>
<artifactId>txlcn-base-b-interface</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
@FeignClient("txlcn-base-b-service")
public interface TestClient extends TestApi {
}
在A服务添加用户的同时,调用B服务添加用户,并且创建zero异常
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Autowired
private TestClient testClient;
@Override
public void insert(TestPO po) {
testMapper.insert(po);
//client调用B服务
testClient.insert(po.getName()+"B");
int i = 100/0;
}
}
重启测试!
浏览器访问: http://localhost:8001/test/insert?name=piaoxu
可以看到,a服务抛出异常,但b服务仍然添加成功了!
现在我们添加上 分布式事务注解
a服务
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Autowired
private TestClient testClient;
@Override
@Transactional
@LcnTransaction
public void insert(TestPO po) {
testMapper.insert(po);
//client调用B服务
testClient.insert(po.getName()+"B");
int i = 100/0;
}
}
b服务
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
@Transactional
@LcnTransaction
public void insert(TestPO po) {
testMapper.insert(po);
}
}
继续访问测试: http://localhost:8001/test/insert?name=piaoxu
可以看到a服务、b服务都没有添加成功!
特别说明: txlcn-tm配置文件解释
server.port=7970
spring.application.name=TransactionManager
eureka.client.service-url.defaultZone=http://admin:admin@localhost:8761/eureka
eureka.instance.appname=transaction-manager
eureka.instance.prefer-ip-address=true
#JDBC 数据库配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://10.115.132.12:3306/tx?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
#数据库方言
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
# 第一次运行可以设置为: create, 为TM创建持久化数据库表
#spring.jpa.hibernate.ddl-auto=validate
spring.jpa.hibernate.ddl-auto=update
# TM监听IP. 默认为 127.0.0.1
tx-lcn.manager.host=127.0.0.1
# TM监听Socket端口. 默认为 ${server.port} - 100
tx-lcn.manager.port=8070
# 心跳检测时间(ms). 默认为 300000
tx-lcn.manager.heart-time=300000
# 分布式事务执行总时间(ms). 默认为36000
tx-lcn.manager.dtx-time=8000
# 参数延迟删除时间单位ms 默认为dtx-time值
tx-lcn.message.netty.attr-delay-time=${tx-lcn.manager.dtx-time}
# 事务处理并发等级. 默认为机器逻辑核心数5倍
tx-lcn.manager.concurrent-level=160
# TM后台登陆密码,默认值为codingapi
tx-lcn.manager.admin-key=codingapi
# 分布式事务锁超时时间 默认为-1,当-1时会用tx-lcn.manager.dtx-time的时间
tx-lcn.manager.dtx-lock-time=${tx-lcn.manager.dtx-time}
# 雪花算法的sequence位长度,默认为12位.
tx-lcn.manager.seq-len=12
# 异常回调开关。开启时请制定ex-url
tx-lcn.manager.ex-url-enabled=false
# 事务异常通知(任何http协议地址。未指定协议时,为TM提供内置功能接口)。默认是邮件通知
tx-lcn.manager.ex-url=/provider/email-to/***@**.com
# 开启日志,默认为false
tx-lcn.logger.driver-class-name=${spring.datasource.driver-class-name}
tx-lcn.logger.jdbc-url=${spring.datasource.url}
tx-lcn.logger.username=${spring.datasource.username}
tx-lcn.logger.password=${spring.datasource.password}
# redis 的设置信息. 线上请用Redis Cluster
spring.redis.host=10.115.132.12
spring.redis.port=6379
spring.redis.password=123456