在微服務中,以springcloud爲例,多個微服務之間通過OpenFeign的方式調用。
現有微服務A、B兩個,a爲A中的事務方法,b是B中的事務方法,假設在A中有一個業務方法businessA,需要調用a,b來完成正常的業務流程處理。
調用順序是,執行完b--->再執行a,b事務方法正常執行,b會提交事務,數據的更改也會被記錄到數據庫中。在執行a的時候出現異常,a事務方法由於拋出異常會正常回滾。此時業務流程是失敗的,但是b的事務已經提交,無法回滾。
這就是微服務中存在的事務問題
Seata可以解決這個問題官方文檔地址
1.下載seata-server,1.1.0下載地址,在Assets有四個選項,這裏選擇seata-server-1.1.0.zip下載
2.下載之後解壓,在conf目錄下自定義配置。打開file.conf文件,更改mode類型爲db,同時在下面的db中根據自己的數據庫配置對應的賬戶、密碼等
## transaction log store, only used in seata-server
store {
## store mode: file、db
mode = "db"
## file store property
file {
## store location dir
dir = "sessionStore"
# branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
maxBranchSessionSize = 16384
# globe session size , if exceeded throws exceptions
maxGlobalSessionSize = 512
# file buffer size , if exceeded allocate new buffer
fileWriteBufferCacheSize = 16384
# when recover batch read size
sessionReloadReadSize = 100
# async, sync
flushDiskMode = async
}
## database store property
db {
## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
datasource = "dbcp"
## mysql/oracle/h2/oceanbase etc.
dbType = "mysql"
driverClassName = "com.mysql.jdbc.Driver"
## 如果要是沒有sata數據庫,要建立一個
url = "jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&characterEncoding=UTF-8"
user = "root"
password = "12345"
minConn = 1
maxConn = 10
## 建好數據庫之後新建下面的這三張表
globalTable = "global_table"
branchTable = "branch_table"
lockTable = "lock_table"
queryLimit = 100
}
}
三張表的建表SQL地址
3.保存file.conf的配置,打開register.conf,這裏的type選擇springcloud的eureka,同時在下面的eureka模塊中,配置eureka註冊中心地址,application="seata-server"(默認是default),修改之後退出
4.進入seata-server解壓之後的bin文件夾,啓動seata-server,Mac下命令行啓動
seata-server.sh -h 127.0.0.1 -p 9091 -m db -n 1
-h: 註冊到註冊中心的ip (要和註冊中心的IP相同,才能註冊到註冊中心上去,本地就是127.0.0.1了)
-p: seata-server的端口號
-m: 全局事務會話信息存儲模式,file、db,優先讀取啓動參數
-n: Server node,多個Server時,需區分各自節點,用於生成不同區間的transactionId,以免衝突
5.啓動之後,搭建微服務A、和B,兩個微服務除了基本的配置之外,加上seata的依賴,springcloud-alibaba-seata依賴(這裏面已經幫我們實現了XID在微服務之間的傳遞),推薦使用1.1.0版本,這個版本數據源可以不用代理,seata會自動代理,同時支持了在yml文件中配置,以前的版本都是要在每個微服務下面加file.conf和register.conf的文件,現在可以直接使用配置
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-seata</artifactId>
<version>2.2.0.RELEASE</version>
<exclusions>
<exclusion>
<artifactId>seata-spring-boot-starter</artifactId>
<groupId>io.seata</groupId>
</exclusion>
</exclusions>
</dependency>
<!--阿里分佈式事務-->
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.1.0</version>
</dependency>
6.在兩個微服務中配置,拿A服務配置舉例:
server:
port: 8084
servlet:
context-path: /clientTwo
tomcat:
connection-timeout: 5000
spring:
main:
allow-bean-definition-overriding: true
application:
name: demo-clientTwo
datasource:
url: jdbc:mysql://localhost:3306/dhb?useUnicode=true&characterEncoding=UTF-8
username: root
password: 12345
# 這裏配置分組
cloud:
alibaba:
seata:
tx-service-group: my_test_tx_group
eureka:
instance:
instance-id: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
lease-renewal-interval-in-seconds: 30
lease-expiration-duration-in-seconds: 90
client:
service-url:
defaultZone: http://localhost:8081/eureka/
registry-fetch-interval-seconds: 15
# 這裏配置的是微服務之間的調用超時時間
feign:
client:
config:
default:
connect-timeout: 4000
read-timeout: 4000
#阿里分佈式事務配置
seata:
service:
vgroup-mapping:
#這裏的組名my_test_tx_group就是上面已經配置過的
# seata-server 對應的就是register.conf裏的application選項的內容
my_test_tx_group: seata-server
grouplist:
#這裏對應的就是上面的seata-server,後面的蠶食seata服務的IP地址和端口號
seata-server: 192.168.0.105:9091
enable-degrade: false
disable-global-transaction: false
mybatis-plus:
mapper-locations: classpath*:/mapper/*.xml
7.在涉及到到分佈式事務的微服務對應的數據庫中,都建立一張undo_log表,undo_log建表地址,undo_log是用來回滾事務的一個記錄表,更多關於undo_log的說明,參考官方的AT工作機制、兩階段提交、undo_log的作用
8.在微服務A的businessA上加入@GlobalTransactional註解
9.測試,通過微服務A調用微服務B中的b事務方法,執行完畢,返回微服務A之後,手動拋出異常,看b事務是否已經回滾
@GlobalTransactional(rollbackFor = Exception.class)
@PostMapping(value = "clientTwoSave")
public Integer save(@RequestBody User user){
com.example.clientone.democlientone.entity.User one = new com.example.clientone.democlientone.entity.User();
BeanUtils.copyProperties(user,one);
System.out.println(RootContext.getXID());
one.setId(4432);
testTransactionService.clientOneSaveUser(one);
// 手動拋出異常
int a = 1/0;
userService.save(user);
return user.getId();
}
查看微服務B對應的user表並沒有新增
10.在b執行完畢之後,返回微服務A,拋出異常之前debug住,查看庫裏的user表和undo_log表
可以看到,b事務正常提交之後,數據庫的數據確實添加進去了,但是當異常發生之後,數據庫裏的數據又被複原到原來的樣子了,在微服務B的控制檯可以看到如下信息
branchId和xid都和undo_log中的數據對應。
這就是使用seata的AT模式完成的控制分佈式事務的流程