當(dāng)前位置:首頁(yè) > IT技術(shù) > 其他 > 正文

atomikos實(shí)現(xiàn)分布式事務(wù)
2022-04-25 23:12:38

date: 2022-04-25
categories: [java, 編程]
tags: [分布式事務(wù)]

概述

多數(shù)據(jù)源單服務(wù)寫入, 分布式事務(wù)實(shí)現(xiàn)

使用隨機(jī)數(shù)控制產(chǎn)生異常

注: 網(wǎng)上很多都是只有多數(shù)據(jù)源配置,實(shí)際不能控制事務(wù)統(tǒng)一回滾,
單服務(wù)場(chǎng)景下如果多個(gè)數(shù)據(jù)源只有一個(gè)寫,剩下都是讀, 則不需要分布式事務(wù)

為減少篇幅,詳細(xì)代碼在代碼倉(cāng)庫(kù),可自行參考

版本

springboot 2.1.7.RELEASE

配置引入

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency>

增加配置類

AtomikosJtaPlatform

JPAAtomikosTransactionConfig Atomikos事務(wù)配置類

PrimaryConfig 主數(shù)據(jù)源配置

SecondaryConfig 其它數(shù)據(jù)源配置

數(shù)據(jù)對(duì)象實(shí)現(xiàn)

User

增加倉(cāng)儲(chǔ)實(shí)現(xiàn)

需要分別實(shí)現(xiàn)primary和secondary, 從而支持多個(gè)數(shù)據(jù)源訪問(wèn)

PrimaryUserRepository

SecondaryUserRepository

實(shí)現(xiàn)服務(wù)類

PrimaryUserService

SecondaryUserService

ExampleService

負(fù)責(zé)統(tǒng)一調(diào)用 PrimaryUserService 和 SecondaryUserService,
模擬一個(gè)服務(wù)同時(shí)訪問(wèn)多個(gè)服務(wù)類(每個(gè)服務(wù)類引用了不同數(shù)據(jù)源)

如果其中某個(gè)服務(wù)拋出異常,則整個(gè)事務(wù)回滾, @Transactional(rollbackOn =
Exception.class) 是必須的

測(cè)試

com.example.springbootatomikos.services.UserServiceTest#testSave

代碼

github地址

gitee地址

本文摘自 :https://www.cnblogs.com/

開通會(huì)員,享受整站包年服務(wù)立即開通 >