哦哇資訊網

SpringCloud系列——TX-LCN分散式事務管理

由 huanzi一qch 發表于 美食2022-12-26

前言

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”?> 4。0。0 cn。huanzi。qch。txlcn txlcn-tm 0。0。1-SNAPSHOT txlcn-tm Tx-Manager(TM),TX-LCN分散式事務框架的獨立服務 <!——繼承資訊——> cn。huanzi。qch parent 1。0。0 <!—— 參照例子引入需要的依賴jar ——> com。codingapi。txlcn txlcn-tm 5。0。2。RELEASE <!—— text報錯,新增一下依賴——> org。springframework。boot spring-boot-starter-test test <!—— 構建工具 ——> org。springframework。boot spring-boot-maven-plugin txlcn-tm

參照官網修改配置檔案,詳細的TM配置請戳:https://www。txlcn。org/zh-cn/docs/setting/manager。html,開發階段最好開啟日誌,並設定為debug等級,這樣方便追蹤排查問題

spring。application。name=txlcn-tmserver。port=7970spring。datasource。driver-class-name=com。mysql。jdbc。Driverspring。datasource。url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghaispring。datasource。username=rootspring。datasource。password=123456spring。jpa。database-platform=org。hibernate。dialect。MySQL5InnoDBDialectspring。jpa。hibernate。ddl-auto=validate# TM後臺登陸密碼tx-lcn。manager。admin-key=123456tx-lcn。manager。host=127。0。0。1tx-lcn。manager。port=8070# 開啟日誌,預設為falsetx-lcn。logger。enabled=truetx-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@EnableTransactionManagerServerpublic 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引入依賴

com。codingapi。txlcn txlcn-tc 5。0。2。RELEASE com。codingapi。txlcn txlcn-txmsg-netty 5。0。2。RELEASE

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依賴

org。springframework。boot spring-boot-starter-jdbc

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# 開啟日誌,預設為falsetx-lcn。logger。enabled=truetx-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

//省略其他程式碼。。。@EnableDistributedTransactionpublic class MyspringbootApplication { public static void main(String[] args) { SpringApplication。run(MyspringbootApplication。class, args); }}

4、在提交本地事務的地方新增

@LcnTransaction

分散式事務註解,PS:@LcnTransaction的target是在方法上的,

@Target({ElementType。METHOD})

測試程式碼

我們挑選之前的兩個專案myspringboot、springdatejpa,按照步驟設定成TC,

並且在兩個TC新增測試介面,

myspringboot

controller

/** * 測試分散式事務 */ @GetMapping(“feign/save”) Result save(UserVo userVo){ //模擬資料 Description description = new Description(); description。setUserId(“111”); description。setDescription(“測試使用者描述”); Result save = descriptionService。save(description); System。out。println(save); return null; }

service

@Override @LcnTransaction//分散式事務 @Transactional //本地事務 public Result save(Description description) { UserVo userVo = new UserVo(); userVo。setUsername(“huanzi”); userVo。setPassword(“123”); //呼叫springdatejpa服務儲存userVo Result 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 save(@RequestBody UserVo userVo);}

springdatejpa

這個原先就已經有對應的save介面,其他的程式碼我們就不貼了,在UserServiceImpl類重寫save方法,在save方法上新增@LcnTransaction註解

@LcnTransaction//分散式事務 @Transactional //本地事務 @Override public Result 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)

SpringCloud系列——TX-LCN分散式事務管理

SpringCloud系列——TX-LCN分散式事務管理

springdatejpa(B)

SpringCloud系列——TX-LCN分散式事務管理

到這裡springdatejpa(B)已經響應了user資料給myspringboot(A),而後收到回滾通知

SpringCloud系列——TX-LCN分散式事務管理

事務提交

我們看一下事務正常提交是怎麼樣的,我們把模擬異常註釋起來,並返回儲存後的資料

//模擬發生異常 //throw new RuntimeException(“business code error”); return Result。of(save);

我們直接從springdatejpa(B)響應資料之後看

myspringboot(A)

SpringCloud系列——TX-LCN分散式事務管理

springdatejpa(B)

SpringCloud系列——TX-LCN分散式事務管理

具體的流程已經事務控制原理可以檢視官網:https://www。txlcn。org/zh-cn/docs/principle/control。html,這裡簡單的貼出官網提供的原理圖:

SpringCloud系列——TX-LCN分散式事務管理

後記

要注意我們的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

版權宣告

作者:huanzi-qch

出處:https://www。cnblogs。com/huanzi-qch

若標題中有“轉載”字樣,則本文版權歸原作者所有。若無轉載字樣,本文版權歸作者所有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連結,否則保留追究法律責任的權利。

TAG: txlcnsave事務nullSpring