SpringCloud分佈式架構給咱們帶來開發上的便利,同時增長了咱們對事務管理的難度,微服務的遍地開花,本地事務已經沒法知足分佈式的要求,由此分佈式事務問題誕生。 分佈式事務被稱爲世界性的難題。html
更多分佈式事務介紹請看這篇文章:再有人問你分佈式事務,把這篇扔給他java
本文記錄整合TX-LCN分佈式事務框架管理分佈式事務,用的版本是5.0.2.RELEASEmysql
TX-LCN分佈式事務框架,LCN並不生產事務,LCN只是本地事務的協調工,LCN是一個高性能的分佈式事務框架,兼容dubbo、springcloud框架,支持RPC框架拓展,支持各類ORM框架、NoSQL、負載均衡、事務補償git
一、一致性,經過TxManager協調控制與事務補償機制確保數據一致性github
二、易用性,僅須要在業務方法上添加@TxTransaction註解便可redis
三、高可用,項目模塊不只可高可用部署,事務協調器也可集羣化部署spring
四、擴展性,支持各類RPC框架擴展,支持通信協議與事務模式擴展sql
更多介紹跟文檔說明請看官網:https://www.txlcn.org/zh-cn/index.html數據庫
咱們按照官方文檔(https://www.txlcn.org/zh-cn/docs/preface.html)一步步操做:apache
建立數據庫、表
建立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
TC端參照官網一步步操做:https://www.txlcn.org/zh-cn/docs/start.html
一、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>
二、配置文件添加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
三、在啓動類上使用 @EnableDistributedTransaction
//省略其餘代碼... @EnableDistributedTransaction public class MyspringbootApplication { public static void main(String[] args) { SpringApplication.run(MyspringbootApplication.class, args); } }
四、在提交本地事務的地方添加
@Target({ElementType.METHOD})
咱們挑選以前的兩個項目myspringboot、springdatejpa,按照步驟設置成TC,
而且在兩個TC添加測試接口,
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); }
這個原先就已經有對應的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),一路下來碰到了一下小問題在這裏總結一下:
一、A調B,A拋出異常,A事務回滾,B事務沒有回滾
緣由:這個是由於剛開始我是在A的controller層調用B,至關於B是一個單獨是事務組,A又是一個單獨的事務組
解決:在A開啓事務後再調用B
代碼已經開源、託管到個人GitHub、碼雲: