前言
SpringCloud分布式架構給我們帶來開發上的便利,同時增加了我們對事務管理的難度,微服務的遍地開花,本地事務已經無法滿足分布式的要求,由此分布式事務問題誕生。 分布式事務被稱為世界性的難題。
更多分布式事務介紹請看這篇文章:再有人問你分布式事務,把這篇扔給他
本文記錄整合TX-LCN分布式事務框架管理分布式事務,用的版本是5.0.2.RELEASE
TX-LCN
簡單介紹
TX-LCN分布式事務框架,LCN並不生產事務,LCN只是本地事務的協調工,LCN是一個高性能的分布式事務框架,兼容dubbo、springcloud框架,支持RPC框架拓展,支持各種ORM框架、NoSQL、負載均衡、事務補償
特性一覽
1、一致性,通過TxManager協調控制與事務補償機制確保數據一致性
2、易用性,僅需要在業務方法上添加@TxTransaction注解即可
3、高可用,項目模塊不僅可高可用部署,事務協調器也可集群化部署
4、擴展性,支持各種RPC框架擴展,支持通訊協議與事務模式擴展
更多介紹跟文檔說明請看官網:https://www.txlcn.org/zh-cn/index.html
擼代碼
我們按照官方文檔(https://www.txlcn.org/zh-cn/docs/preface.html)一步步操作:
Tx-Manager
創建數據庫、表
-
創建MySQL數據庫, 名稱為:tx-manager(我們直接選擇在我們自己的數據庫下面創建表就行了,這里就不創建這個數據庫)
-
創建數據表:t_tx_exception
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 NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
下載官網提供的最新版的TM項目,修改配置文件(PS:由於官網的下載地址打不開,我們去GitHub上面下載例子:https://github.com/codingapi/txlcn-demo),參考txlcn-demo-tm工程,在我們之前的項目下面創建一個springboot項目叫txlcn-tm
創建好springboot項目后,參照例子修改pom.xml文件
<?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>cn.huanzi.qch.txlcn</groupId> <artifactId>txlcn-tm</artifactId> <version>0.0.1-SNAPSHOT</version> <name>txlcn-tm</name> <description>Tx-Manager(TM),TX-LCN分布式事務框架的獨立服務</description> <!--繼承信息--> <parent> <groupId>cn.huanzi.qch</groupId> <artifactId>parent</artifactId> <version>1.0.0</version> </parent> <dependencies> <!-- 參照例子引入需要的依賴jar --> <dependency> <groupId>com.codingapi.txlcn</groupId> <artifactId>txlcn-tm</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!-- text報錯,添加一下依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <!-- 構建工具 --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <finalName>txlcn-tm</finalName> </build> </project>
參照官網修改配置文件,詳細的TM配置請戳:https://www.txlcn.org/zh-cn/docs/setting/manager.html,開發階段最好開啟日志,並設置為debug等級,這樣方便追蹤排查問題
spring.application.name=txlcn-tm server.port=7970 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?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=validate # TM后台登陸密碼 tx-lcn.manager.admin-key=123456 tx-lcn.manager.host=127.0.0.1 tx-lcn.manager.port=8070 # 開啟日志,默認為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}
logging.level.com.codingapi.txlcn=DEBUG #redis 主機 spring.redis.host=127.0.0.1 #redis 端口 spring.redis.port=6379 #redis 密碼 spring.redis.password=
在啟動類添加注解 @EnableTransactionManagerServer
package cn.huanzi.qch.txlcn.tm; import com.codingapi.txlcn.tm.config.EnableTransactionManagerServer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableTransactionManagerServer public class TxlcnTmApplication { public static void main(String[] args) { SpringApplication.run(TxlcnTmApplication.class, args); } }
把我們的Redis服務運行起來,然后啟動txlcn-tm,啟動成功后訪問tm后台管理系統,使用默認密碼登錄(可以配置登錄密碼),訪問 http://127.0.0.1:7970/admin/index.html進入管理后台,默認密碼是codingapi,我們這里配置了123456
啟動TM之前記得先啟動我們的Redis服務,到這里,我們的tm搭建成功,更多TM介紹,請看官網TM管理手冊:https://www.txlcn.org/zh-cn/docs/manageradmin.html
Tx-Client
TC端參照官網一步步操作:https://www.txlcn.org/zh-cn/docs/start.html
1、TC引入依賴
<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>
PS:如果你沒有添加jdbc驅動,啟動的時候會報錯
Parameter 0 of constructor in com.codingapi.txlcn.tc.core.transaction.txc.analy.TableStructAnalyser required a bean of type 'javax.sql.DataSource' that could not be found.
因此要添加jdbc依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
2、配置文件添加TM地址跟監聽端口,如果TM是默認8070端口,且跟TC部署在同一台機器,可以忽略這個配置,並且開啟日志,開發階段最好開啟日志,並設置為debug等級,這樣方便追蹤排查問題
# 是否啟動LCN負載均衡策略(優化選項,開啟與否,功能不受影響)
tx-lcn.ribbon.loadbalancer.dtx.enabled=true
# 默認之配置為TM的本機默認端口
tx-lcn.client.manager-address=127.0.0.1:8070
# 開啟日志,默認為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}
logging.level.com.codingapi.txlcn=DEBUG
3、在啟動類上使用 @EnableDistributedTransaction
//省略其他代碼... @EnableDistributedTransaction public class MyspringbootApplication { public static void main(String[] args) { SpringApplication.run(MyspringbootApplication.class, args); } }
4、在提交本地事務的地方添加
@Target({ElementType.METHOD})
測試代碼
我們挑選之前的兩個項目myspringboot、springdatejpa,按照步驟設置成TC,
並且在兩個TC添加測試接口,
myspringboot
controller
/** * 測試分布式事務 */ @GetMapping("feign/save") Result<UserVo> save(UserVo userVo){ //模擬數據 Description description = new Description(); description.setUserId("111"); description.setDescription("測試用戶描述"); Result<Description> save = descriptionService.save(description); System.out.println(save); return null; }
service
@Override @LcnTransaction//分布式事務 @Transactional //本地事務 public Result<Description> save(Description description) { UserVo userVo = new UserVo(); userVo.setUsername("huanzi"); userVo.setPassword("123"); //調用springdatejpa服務保存userVo Result<UserVo> result = myspringbootFeign.save(userVo); System.out.println(result); //myspringboot本地服務保存description Description save = descriptionRepository.save(description); System.out.println(save); //模擬發生異常 throw new RuntimeException("business code error"); }
feign
@FeignClient(name = "springdatejpa", path = "/user/",fallback = MyspringbootFeignFallback.class,fallbackFactory = MyspringbootFeignFallbackFactory.class) public interface MyspringbootFeign { @RequestMapping(value = "save") Result<UserVo> save(@RequestBody UserVo userVo); }
springdatejpa
這個原先就已經有對應的save接口,其他的代碼我們就不貼了,在UserServiceImpl類重寫save方法,在save方法上添加@LcnTransaction注解
@LcnTransaction//分布式事務 @Transactional //本地事務 @Override public Result<UserVo> save(UserVo entity) { User user = userRepository.save(FastCopy.copy(entity, User.class)); return Result.of(FastCopy.copy(user, UserVo.class)); }
演示效果
啟動所有項目,TM跟Redis服務也要記得啟動
查看TM后台,可以看到成功注冊了兩個TC
訪問http://localhost:10010/myspringboot/feign/save,被單點登錄攔截,登錄后跳轉正常跳轉該接口,這些就不再演示了,下面直接看后台debug日志
調用流程
myspringboot(A) ---> springdatejpa(B)
事務回滾
myspringboot(A)
springdatejpa(B)
到這里springdatejpa(B)已經響應了user數據給myspringboot(A),而后收到回滾通知
事務提交
我們看一下事務正常提交是怎么樣的,我們把模擬異常注釋起來,並返回保存后的數據
//模擬發生異常 //throw new RuntimeException("business code error"); return Result.of(save);
我們直接從springdatejpa(B)響應數據之后看
myspringboot(A)
springdatejpa(B)
具體的流程已經事務控制原理可以查看官網:https://www.txlcn.org/zh-cn/docs/principle/control.html,這里簡單的貼出官網提供的原理圖:
后記
要注意我們的springboot版本跟txlcn的版本是不是兼容,按照官網的快速開始(https://www.txlcn.org/zh-cn/docs/start.html),以及參考官方例子(https://github.com/codingapi/txlcn-demo),一路下來碰到了一下小問題在這里總結一下:
1、A調B,A拋出異常,A事務回滾,B事務沒有回滾
原因:這個是因為剛開始我是在A的controller層調用B,相當於B是一個單獨是事務組,A又是一個單獨的事務組
解決:在A開啟事務后再調用B
代碼開源
代碼已經開源、托管到我的GitHub、碼雲:
GitHub:https://github.com/huanzi-qch/springCloud
碼雲:https://gitee.com/huanzi-qch/springCloud