分布式事務(wù)理論:分布式事務(wù)
分布式事務(wù)解決方案之2PC(兩階段提交)
2PC即兩階段提交協(xié)議萨醒,是將整個(gè)事務(wù)流程分為兩個(gè)階段并鸵,準(zhǔn)備階段(Prepare phase)、提交階段(commit phase)捌蚊,2是指兩個(gè)階段弯洗,P是指準(zhǔn)備階段,C是指提交階段逢勾。
整個(gè)事務(wù)過程由事務(wù)管理器和參與者組成牡整,事務(wù)管理器負(fù)責(zé)決策整個(gè)分布式事務(wù)的提交和回滾,事務(wù)參與者負(fù)責(zé)自己本地事務(wù)的提交和回滾溺拱。
在計(jì)算機(jī)中部分關(guān)系數(shù)據(jù)庫如Oracle逃贝、MySQL支持兩階段提交協(xié)議,如下圖:
1迫摔、準(zhǔn)備階段(Prepare phase):事務(wù)管理器給每個(gè)參與者發(fā)送Prepare消息沐扳,每個(gè)數(shù)據(jù)庫參與者在本地執(zhí)行事務(wù),并寫本地的Undo/Redo日志句占,此時(shí)事務(wù)沒有提交沪摄。(Undo日志是記錄修改前的數(shù)據(jù),用于數(shù)據(jù)庫回滾,Redo日志是記錄修改后的數(shù)據(jù)杨拐,用于提交事務(wù)后寫入數(shù)據(jù)文件)
2祈餐、提交階段(commit phase):如果事務(wù)管理器收到了參與者的執(zhí)行失敗或者超時(shí)消息時(shí),直接給每個(gè)參與者發(fā)送回滾(Rollback)消息哄陶;否則帆阳,發(fā)送提交(Commit)消息;參與者根據(jù)事務(wù)管理器的指令執(zhí)行提交或者回滾操作屋吨,并釋放事務(wù)處理過程中使用的鎖資源蜒谤。注意:必須在最后階段釋放鎖資源。
下圖展示了2PC的兩個(gè)階段至扰,分成功和失敗兩個(gè)情況說明:
成功情況:
失敗情況:
解決方案
XA方案
2PC的傳統(tǒng)方案是在數(shù)據(jù)庫層面實(shí)現(xiàn)的鳍徽,如Oracle、MySQL都支持2PC協(xié)議敢课,為了統(tǒng)一標(biāo)準(zhǔn)減少行業(yè)內(nèi)不必要的對接成本阶祭,需要制定標(biāo)準(zhǔn)化的處理模型及接口標(biāo)準(zhǔn),國際開放標(biāo)準(zhǔn)組織Open Group定義了分布式事務(wù)處理模型DTP(Distributed Transaction Processing Reference Model)翎猛。
為了讓大家更明確XA方案的內(nèi)容程胖翰,下面新用戶注冊送積分為例來說明:
執(zhí)行流程如下:
- 1、應(yīng)用程序(AP)持有用戶庫和積分庫兩個(gè)數(shù)據(jù)源切厘。
- 2萨咳、應(yīng)用程序(AP)通過TM通知用戶庫RM新增用戶,同時(shí)通知積分庫RM為該用戶新增積分疫稿,RM此時(shí)并未提交事務(wù)培他,此時(shí)用戶和積分資源鎖定。
- 3遗座、TM收到執(zhí)行回復(fù)舀凛,只要有一方失敗則分別向其他RM發(fā)起回滾事務(wù),回滾完畢途蒋,資源鎖釋放猛遍。
- 4、TM收到執(zhí)行回復(fù)号坡,全部成功懊烤,此時(shí)向所有RM發(fā)起提交事務(wù),提交完畢宽堆,資源鎖釋放腌紧。
DTP模型定義如下角色:
- AP(Application Program):即應(yīng)用程序,可以理解為使用DTP分布式事務(wù)的程序畜隶。
- RM(Resource Manager):即資源管理器壁肋,可以理解為事務(wù)的參與者号胚,一般情況下是指一個(gè)數(shù)據(jù)庫實(shí)例,通過資源管理器對該數(shù)據(jù)庫進(jìn)行控制浸遗,資源管理器控制著分支事務(wù)猫胁。
- TM(Transaction Manager):事務(wù)管理器,負(fù)責(zé)協(xié)調(diào)和管理事務(wù)乙帮,事務(wù)管理器控制著全局事務(wù)杜漠,管理事務(wù)生命周期极景,并協(xié)調(diào)各個(gè)RM察净。全局事務(wù)是指分布式事務(wù)處理環(huán)境中,需要操作多個(gè)數(shù)據(jù)庫共同完成一個(gè)工作盼樟,這個(gè)工作即是一個(gè)全局事務(wù)氢卡。
- DTP模型定義TM和RM之間通訊的接口規(guī)范叫XA,簡單理解為數(shù)據(jù)庫提供的2PC接口協(xié)議晨缴,基于數(shù)據(jù)庫的XA協(xié)議來實(shí)現(xiàn)2PC又稱為XA方案译秦。
以上三個(gè)角色之間的交互方式如下:- 1)TM向AP提供 應(yīng)用程序編程接口,AP通過TM提交及回滾事務(wù)击碗。
- 2)TM交易中間件通過XA接口來通知RM數(shù)據(jù)庫事務(wù)的開始筑悴、結(jié)束以及提交、回滾等稍途。
總結(jié):
整個(gè)2PC的事務(wù)流程涉及到三個(gè)角色AP阁吝、RM、TM械拍。AP指的是使用2PC分布式事務(wù)的應(yīng)用程序突勇;RM指的是資源管理器,它控制著分支事務(wù)坷虑;TM指的是事務(wù)管理器甲馋,它控制著整個(gè)全局事務(wù)。
1)在準(zhǔn)備階段RM執(zhí)行實(shí)際的業(yè)務(wù)操作迄损,但不提交事務(wù)定躏,資源鎖定;
2)在提交階段TM會接受RM在準(zhǔn)備階段的執(zhí)行回復(fù)芹敌,只要有任一個(gè)RM執(zhí)行失敗痊远,TM會通知所有RM執(zhí)行回滾操作,否則党窜,TM將會通知所有RM提交該事務(wù)拗引。提交階段結(jié)束資源鎖釋放。
應(yīng)用落地方案是:atomikos + druid的DruidXADataSource
需要引入maven依賴:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency>
XA方案的問題:
- 1幌衣、需要本地?cái)?shù)據(jù)庫支持XA協(xié)議矾削。
- 2壤玫、資源鎖需要等到兩個(gè)階段結(jié)束才釋放,性能較差哼凯。
Seata方案
Seata是由阿里中間件團(tuán)隊(duì)發(fā)起的開源項(xiàng)目 Fescar欲间,后更名為Seata,它是一個(gè)是開源的分布式事務(wù)框架断部。
傳統(tǒng)2PC的問題在Seata中得到了解決猎贴,它通過對本地關(guān)系數(shù)據(jù)庫的分支事務(wù)的協(xié)調(diào)來驅(qū)動(dòng)完成全局事務(wù),是工作在應(yīng)用層的中間件蝴光。主要優(yōu)點(diǎn)是性能較好她渴,且不長時(shí)間占用連接資源,它以高效并且對業(yè)務(wù)0侵入的方式解決微服務(wù)場景下面臨的分布式事務(wù)問題蔑祟,它目前提供AT模式趁耗、XA模式、Saga模式和TCC模式的分布式事務(wù)解決方案疆虚。
Seata的設(shè)計(jì)思想如下:
Seata的設(shè)計(jì)目標(biāo)其一是對業(yè)務(wù)無侵入苛败,因此從業(yè)務(wù)無侵入的2PC方案著手,在傳統(tǒng)2PC的基礎(chǔ)上演進(jìn)径簿,并解決2PC方案面臨的問題罢屈。
Seata把一個(gè)分布式事務(wù)理解成一個(gè)包含了若干分支事務(wù)的全局事務(wù)。全局事務(wù)的職責(zé)是協(xié)調(diào)其下管轄的分支事務(wù)達(dá)成一致篇亭,要么一起成功提交缠捌,要么一起失敗回滾。此外暗赶,通常分支事務(wù)本身就是一個(gè)關(guān)系數(shù)據(jù)庫的本地事務(wù)鄙币。
下圖是全局事務(wù)與分支事務(wù)的關(guān)系圖:
Seata有3個(gè)基本組成部分:
Transaction Coordinator (TC): 事務(wù)協(xié)調(diào)器,它是獨(dú)立的中間件蹂随,需要獨(dú)立部署運(yùn)行十嘿,它維護(hù)全局事務(wù)的運(yùn)行狀態(tài),接收TM指令發(fā)起全局事務(wù)的提交與回滾岳锁,負(fù)責(zé)與RM通信協(xié)調(diào)各各分支事務(wù)的提交或回滾绩衷。
Transaction Manager (TM): 事務(wù)管理器,TM需要嵌入應(yīng)用程序中工作激率,它負(fù)責(zé)開啟一個(gè)全局事務(wù)咳燕,并最終向TC發(fā)起全局提交或全局回滾的指令。
Resource Manager (RM): 控制分支事務(wù)乒躺,負(fù)責(zé)分支注冊招盲、狀態(tài)匯報(bào),并接收事務(wù)協(xié)調(diào)器TC的指令嘉冒,驅(qū)動(dòng)分支(本地)事務(wù)的提交和回滾曹货。
Seata管理的分布式事務(wù)的典型生命周期:
- 1咆繁、TM要求TC開始一項(xiàng)新的全局事務(wù),TC生成代表全局事務(wù)的XID顶籽。
- 2玩般、XID通過微服務(wù)的調(diào)用鏈傳播。
- 3礼饱、RM將本地事務(wù)注冊為XID到TC的相應(yīng)全局事務(wù)的分支坏为。
- 4、TM要求TC提交或回退XID的相應(yīng)全局事務(wù)镊绪。
- 5匀伏、TC驅(qū)動(dòng)XID對應(yīng)的全局事務(wù)下的所有分支事務(wù)以完成分支提交或回滾。
Seata實(shí)現(xiàn)2PC與傳統(tǒng)2PC的差別:
架構(gòu)層次方面镰吆,傳統(tǒng)2PC方案的 RM 實(shí)際上是在數(shù)據(jù)庫層帘撰,RM 本質(zhì)上就是數(shù)據(jù)庫自身跑慕,通過 XA 協(xié)議實(shí)現(xiàn)万皿,而Seata的 RM 是以jar包的形式作為中間件層部署在應(yīng)用程序這一側(cè)的。
兩階段提交方面核行,傳統(tǒng)2PC無論第二階段的決議是commit還是rollback牢硅,事務(wù)性資源的鎖都要保持到Phase2完成才釋放。而Seata的做法是在Phase1 就將本地事務(wù)提交芝雪,這樣就可以省去Phase2持鎖的時(shí)間减余,整體提高效率。
Seata實(shí)現(xiàn)2PC事務(wù)
微服務(wù)版本:
Seata-Server:1.3.0
Nacos-Server:1.3.1
SpringBoot:2.2.10.RELEASE
spring-cloud-dependencies:Hoxton.SR8
spring-cloud-alibaba-dependencies:2.2.1.RELEASE
業(yè)務(wù)說明
本示例通過Seata中間件實(shí)現(xiàn)分布式事務(wù)惩系,模擬三個(gè)賬戶的轉(zhuǎn)賬交易過程位岔。
兩個(gè)賬戶在三個(gè)不同的銀行(張三在bank1、李四在bank2)堡牡,bank1和bank2是兩個(gè)個(gè)微服務(wù)抒抬。交易過程是,張三給李四轉(zhuǎn)賬指定金額晤柄。
上述交易步驟擦剑,要么一起成功,要么一起失敗芥颈,必須是一個(gè)整體性的事務(wù)惠勒。
Nacos服務(wù)(參考:Spring Cloud Alibaba Nacos作為服務(wù)注冊發(fā)現(xiàn)組件)
下載Nacos服務(wù)端壓縮包:https://github.com/alibaba/nacos/releases
Seata服務(wù)端(TC)部署
下載Seata服務(wù)端壓縮包:https://github.com/seata/seata/releases
Seata配置
1、修改conf目錄中 flie.conf 文件爬坑,修改事務(wù)日志存儲模式為 db 及數(shù)據(jù)庫連接信息纠屋,且新增service模塊,如下:
transport {
# tcp udt unix-domain-socket
type = "TCP"
#NIO NATIVE
server = "NIO"
#enable heartbeat
heartbeat = true
# the client batch send request enable
enableClientBatchSendRequest = false
#thread factory for netty
threadFactory {
bossThreadPrefix = "NettyBoss"
workerThreadPrefix = "NettyServerNIOWorker"
serverExecutorThreadPrefix = "NettyServerBizHandler"
shareBossWorker = false
clientSelectorThreadPrefix = "NettyClientSelector"
clientSelectorThreadSize = 1
clientWorkerThreadPrefix = "NettyClientWorkerThread"
# netty boss thread size,will not be used for UDT
bossThreadSize = 1
#auto default pin or 8
workerThreadSize = "default"
}
shutdown {
# when destroy server, wait seconds
wait = 3
}
serialization = "seata"
compressor = "none"
}
#這里手動(dòng)加入service模塊
service {
#transaction service group mapping
#修改盾计,可不改,my_test_tx_group隨便起名字售担。
vgroup_mapping.seata_bank1_group = "default"
vgroup_mapping.seata_bank2_group = "default"
#only support when registry.type=file, please don't set multiple addresses
# 此服務(wù)的地址
default.grouplist = "127.0.0.1:8091"
#disable seata
disableGlobalTransaction = false
}
## transaction log store, only used in server side
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 = "druid"
## mysql/oracle/postgresql/h2/oceanbase etc.
dbType = "mysql"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://127.0.0.1:3306/seata"
user = "root"
password = "yibo"
minConn = 5
maxConn = 30
globalTable = "global_table"
branchTable = "branch_table"
lockTable = "lock_table"
queryLimit = 100
}
}
## server configuration, only used in server side
server {
recovery {
#schedule committing retry period in milliseconds
committingRetryPeriod = 1000
#schedule asyn committing retry period in milliseconds
asynCommittingRetryPeriod = 1000
#schedule rollbacking retry period in milliseconds
rollbackingRetryPeriod = 1000
#schedule timeout retry period in milliseconds
timeoutRetryPeriod = 1000
}
undo {
logSaveDays = 7
#schedule delete expired undo_log in milliseconds
logDeletePeriod = 86400000
}
#check auth
enableCheckAuth = true
#unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent
maxCommitRetryTimeout = "-1"
maxRollbackRetryTimeout = "-1"
rollbackRetryTimeoutUnlockEnable = false
}
## metrics configuration, only used in server side
metrics {
enabled = false
registryType = "compact"
# multi exporters use comma divided
exporterList = "prometheus"
exporterPrometheusPort = 9898
}
由于我們使用了db模式存儲事務(wù)日志,所以我們需要?jiǎng)?chuàng)建一個(gè)seata數(shù)據(jù)庫灼舍,Seata數(shù)據(jù)庫表初始化腳本:https://github.com/seata/seata/tree/1.4.0/script/server/db
2吼和、修改注冊中心和配置中心,使用nacos作為注冊中心和配置中心骑素,即修改 conf目錄中 registry.conf 文件炫乓,如下:
registry {
# file 、nacos 献丑、eureka末捣、redis、zk创橄、consul箩做、etcd3、sofa
type = "nacos"
nacos {
application = "seata-server"
serverAddr = "127.0.0.1:8848"
group = "SEATA_GROUP"
namespace = ""
cluster = "default"
username = ""
password = ""
}
eureka {
serviceUrl = "http://localhost:8761/eureka"
application = "default"
weight = "1"
}
redis {
serverAddr = "localhost:6379"
db = 0
password = ""
cluster = "default"
timeout = 0
}
zk {
cluster = "default"
serverAddr = "127.0.0.1:2181"
sessionTimeout = 6000
connectTimeout = 2000
username = ""
password = ""
}
consul {
cluster = "default"
serverAddr = "127.0.0.1:8500"
}
etcd3 {
cluster = "default"
serverAddr = "http://localhost:2379"
}
sofa {
serverAddr = "127.0.0.1:9603"
application = "default"
region = "DEFAULT_ZONE"
datacenter = "DefaultDataCenter"
cluster = "default"
group = "SEATA_GROUP"
addressWaitTime = "3000"
}
file {
name = "file.conf"
}
}
config {
# file妥畏、nacos 邦邦、apollo、zk醉蚁、consul燃辖、etcd3
type = "nacos"
nacos {
serverAddr = "127.0.0.1:8848"
namespace = ""
group = "SEATA_GROUP"
username = ""
password = ""
}
consul {
serverAddr = "127.0.0.1:8500"
}
apollo {
appId = "seata-server"
apolloMeta = "http://192.168.1.204:8801"
namespace = "application"
}
zk {
serverAddr = "127.0.0.1:2181"
sessionTimeout = 6000
connectTimeout = 2000
username = ""
password = ""
}
etcd3 {
serverAddr = "http://localhost:2379"
}
file {
name = "file.conf"
}
}
3、配置config.txt
官網(wǎng)seata-server-0.9.0的conf目錄下有該文件网棍,seata-server-1.0.0及以后版本的conf目錄下沒有nacos-config.txt文件黔龟,從seata-1.3.0源碼中找到config.txt文件,文件位置:seata-1.3.0/script/config-center
滥玷,或者從https://github.com/seata/seata/tree/1.3.0/script/config-center下載氏身,修改store.db相關(guān)內(nèi)容和service.vgroupMapping相關(guān)內(nèi)容,如下:
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
transport.threadFactory.bossThreadPrefix=NettyBoss
transport.threadFactory.workerThreadPrefix=NettyServerNIOWorker
transport.threadFactory.serverExecutorThreadPrefix=NettyServerBizHandler
transport.threadFactory.shareBossWorker=false
transport.threadFactory.clientSelectorThreadPrefix=NettyClientSelector
transport.threadFactory.clientSelectorThreadSize=1
transport.threadFactory.clientWorkerThreadPrefix=NettyClientWorkerThread
transport.threadFactory.bossThreadSize=1
transport.threadFactory.workerThreadSize=default
transport.shutdown.wait=3
# 修改為自己的服務(wù)組名惑畴,各個(gè)微服務(wù)之間使用不同的服務(wù)組名
service.vgroupMapping.seata_bank1_group=default
service.vgroupMapping.seata_bank2_group=default
service.default.grouplist=127.0.0.1:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
client.rm.asyncCommitBufferLimit=10000
client.rm.lock.retryInterval=10
client.rm.lock.retryTimes=30
client.rm.lock.retryPolicyBranchRollbackOnConflict=true
client.rm.reportRetryCount=5
client.rm.tableMetaCheckEnable=false
client.rm.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
store.mode=file
store.file.dir=file_store/data
store.file.maxBranchSessionSize=16384
store.file.maxGlobalSessionSize=512
store.file.fileWriteBufferCacheSize=16384
store.file.flushDiskMode=async
store.file.sessionReloadReadSize=100
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true
store.db.user=root
store.db.password=yibo
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
store.redis.host=127.0.0.1
store.redis.port=6379
store.redis.maxConn=10
store.redis.minConn=1
store.redis.database=0
store.redis.password=null
store.redis.queryLimit=100
server.recovery.committingRetryPeriod=1000
server.recovery.asynCommittingRetryPeriod=1000
server.recovery.rollbackingRetryPeriod=1000
server.recovery.timeoutRetryPeriod=1000
server.maxCommitRetryTimeout=-1
server.maxRollbackRetryTimeout=-1
server.rollbackRetryTimeoutUnlockEnable=false
client.undo.dataValidation=true
client.undo.logSerialization=jackson
client.undo.onlyCareUpdateColumns=true
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000
client.undo.logTable=undo_log
client.log.exceptionRate=100
transport.serialization=seata
transport.compressor=none
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
并將config.txt文件放到Seata-Server的conf文件夾的同級目錄里面
4蛋欣、新增nacos-config.sh文件
- 從seata-1.3.0源碼中找到nacos-config.sh文件,文件位置:
seata-1.3.0/script/config-server/nacos/nacos-config.sh
- 從https://github.com/seata/seata/tree/1.3.0/script/config-center/nacos下載
文件內(nèi)容如下:
#!/usr/bin/env bash
# Copyright 1999-2019 Seata.io Group.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at桨菜、
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
while getopts ":h:p:g:t:u:w:" opt
do
case $opt in
h)
host=$OPTARG
;;
p)
port=$OPTARG
;;
g)
group=$OPTARG
;;
t)
tenant=$OPTARG
;;
u)
username=$OPTARG
;;
w)
password=$OPTARG
;;
?)
echo " USAGE OPTION: $0 [-h host] [-p port] [-g group] [-t tenant] [-u username] [-w password] "
exit 1
;;
esac
done
if [[ -z ${host} ]]; then
host=localhost
fi
if [[ -z ${port} ]]; then
port=8848
fi
if [[ -z ${group} ]]; then
group="SEATA_GROUP"
fi
if [[ -z ${tenant} ]]; then
tenant=""
fi
if [[ -z ${username} ]]; then
username=""
fi
if [[ -z ${password} ]]; then
password=""
fi
nacosAddr=$host:$port
contentType="content-type:application/json;charset=UTF-8"
echo "set nacosAddr=$nacosAddr"
echo "set group=$group"
failCount=0
tempLog=$(mktemp -u)
function addConfig() {
curl -X POST -H "${contentType}" "http://$nacosAddr/nacos/v1/cs/configs?dataId=$1&group=$group&content=$2&tenant=$tenant&username=$username&password=$password" >"${tempLog}" 2>/dev/null
if [[ -z $(cat "${tempLog}") ]]; then
echo " Please check the cluster status. "
exit 1
fi
if [[ $(cat "${tempLog}") =~ "true" ]]; then
echo "Set $1=$2 successfully "
else
echo "Set $1=$2 failure "
(( failCount++ ))
fi
}
count=0
for line in $(cat $(dirname "$PWD")/config.txt | sed s/[[:space:]]//g); do
(( count++ ))
key=${line%%=*}
value=${line#*=}
addConfig "${key}" "${value}"
done
echo "========================================================================="
echo " Complete initialization parameters, total-count:$count , failure-count:$failCount "
echo "========================================================================="
if [[ ${failCount} -eq 0 ]]; then
echo " Init nacos config finished, please start seata-server. "
else
echo " init nacos config fail. "
fi
注意:config.txt文件必須在nacos-config.sh的上級目錄豁状,即nacos-config.sh放在conf目錄中
5、使用nacos-config.sh同步配置到nacos
在Windows系統(tǒng)中倒得,在Seata-Server的conf目錄中采用Git Bash執(zhí)行
執(zhí)行完成后nacos會新增seata配置泻红,如下圖:
高可用部署 Seata 服務(wù)端 - HA Cluster
-
前提條件:
- seata-server 使用 nacos 作為注冊中心和配置中心
- 使用DB存儲模式, 參見上面
分別啟動(dòng) seata-server
啟動(dòng)服務(wù)霞掺,多環(huán)境配置參考 谊路,注: 堆內(nèi)存建議分配2G,堆外內(nèi)存1G
# 實(shí)際使用 -Xmx512m -Xms512m -Xmn256m 也沒發(fā)現(xiàn)什么問題
sh seata-server512.sh -h 127.0.0.1 -p 8091 -m db
-h: 注冊到注冊中心的ip , 雖然是可選菩彬,但建議帶上
-p: Server rpc 監(jiān)聽端口
-m: 全局事務(wù)會話信息存儲模式缠劝,file潮梯、db,優(yōu)先讀取啟動(dòng)參數(shù)
-n: Server node惨恭,多個(gè)Server時(shí)秉馏,需區(qū)分各自節(jié)點(diǎn),用于生成不同區(qū)間的transactionId脱羡,以免沖突
-e: 多環(huán)境配置
sh seata-server.sh -p 8091 -h 192.168.1.11 -m db -n 1
sh seata-server.sh -p 8091 -h 192.168.1.12 -m db -n 2
# 注意要設(shè)置 -n: Server node 萝究,多個(gè)Server時(shí),需區(qū)分各自節(jié)點(diǎn)锉罐,用于生成不同區(qū)間的transactionId帆竹,以免沖突
windows單機(jī)演示:
seata-server.bat -p 8091 -h 127.0.0.1 -m db -n 1
seata-server.bat -p 18091 -h 127.0.0.1 -m db -n 2
seata-server.bat -p 8091 -h 127.0.0.1 -m file -n 1
seata-server.bat -p 8092 -h 127.0.0.1 -m file -n 2
登錄nacos , 查看 seata 命名空間下的 服務(wù)列表脓规,會發(fā)現(xiàn)有兩個(gè)名稱為 serverAddr 的服務(wù)
至此 seata-server 集群已經(jīng)搭建完成栽连,但是 setata rm 和 tm 客戶端如何使用這個(gè)集群呢?
-
Client端配置:在Spring Boot項(xiàng)目侨舆,使用的是 seata-spring-boot-starter 依賴秒紧,可以從源碼的 script --> client -->spring 目錄下 復(fù)制 seata 配置,但是這個(gè)配置默認(rèn)是使用 file 類型的注冊中心
- file 類型下态罪, 項(xiàng)目會通過
seata.service.grouplist.default=127.0.0.1:8091
配置的內(nèi)容連接 seata-server 噩茄, 即使不配置 seata.service.grouplist.default ,仍然會用 127.0.0.1:8091 嘗試連接 seata-server - 官網(wǎng)說 grouplist 只有在 file 類型才會被程序讀取复颈,其他類型的注冊中心不會讀取
- 由于spring-boot本身配置文件語法的要求,這個(gè)地方需要將file.conf中的default.grouplist寫成grouplist.default, 效果是一樣的.
- file 類型下态罪, 項(xiàng)目會通過
為了讓 setata rm 和 tm 客戶端連接seata-server集群沥割,需要利用注冊中心的注冊發(fā)現(xiàn)機(jī)制耗啦,讓注冊中心找到seata-server集群的IP;
各微服務(wù)配置
- 1机杜、引入maven
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.10.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<exclusions>
<exclusion>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-seata</artifactId>
<version>2.2.0.RELEASE</version>
<exclusions>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
</exclusion>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR8</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.1.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<configurationFile>
${basedir}/src/main/resources/generator/generatorConfig.xml
</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.1.5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
2枚碗、分別在各業(yè)務(wù)數(shù)據(jù)庫中創(chuàng)建undo_log表东揣,此表為seata框架使用,sql地址:https://github.com/seata/seata/blob/develop/script/client/at/db/mysql.sql
3、配置application.properties文件
spring.application.name=seata-bank1
server.port=8084
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
spring.cloud.nacos.discovery.group=SEATA_GROUP
seata.enabled=true
#這里的名字與file.conf中vgroup_mapping.my_test_tx_group = "default"相同
seata.tx-service-group=seata_bank1_group
seata.application-id=${spring.application.name}
#這里的名字與file.conf中vgroup_mapping.my_test_tx_group = "default"相同
seata.service.vgroup-mapping.seata_bank1_group=default
#這里的名字與file.conf中default.grouplist = "127.0.0.1:8091"相同
seata.service.grouplist.default=127.0.0.1:8091
seata.enable-auto-data-source-proxy=true
seata.config.type=nacos
#這里的名字就是registry.conf中 nacos的group名字
seata.config.nacos.group=SEATA_GROUP
#這里的地址就是你的nacos的地址,可以更換為線上
seata.config.nacos.server-addr=127.0.0.1:8848
seata.registry.type=nacos
seata.registry.nacos.application=seata-server
#這里的地址就是你的nacos的地址,可以更換為線上
seata.registry.nacos.server-addr=127.0.0.1:8848
#這里的名字就是registry.conf中 nacos的group名字
seata.registry.nacos.group=SEATA_GROUP
seata.registry.nacos.cluster=default
- 4卷雕、啟動(dòng)類配置
@MapperScan("com.yibo.seata.mapper")//掃描mybatis的指定包下的接口
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class Seata1Application {
public static void main(String[] args) {
SpringApplication.run(Seata1Application.class,args);
}
}
業(yè)務(wù)邏輯實(shí)現(xiàn)
- 1、Controller實(shí)現(xiàn)
@RestController
@RequestMapping("/bank1")
public class Bank1Controller {
@Autowired
private AccountService accountService;
@GetMapping("/transfer/{amount}")
public String transfer(@PathVariable("amount") Long amount){
accountService.updateAccountBalance("1",amount);
return "bank1"+amount;
}
}
- 2磅甩、Service實(shí)現(xiàn)糊识,@GlobalTransactional注解用以開啟全局事務(wù),@Transactional注解用于分支事務(wù)
@Service
@Slf4j
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountInfoMapper accountInfoMapper;
@Autowired
private Bank2Client bank2Client;
@Transactional
@GlobalTransactional//開啟全局事務(wù)
public void updateAccountBalance(String accountNo, Long amount) {
log.info("bank1 service begin,XID:{}", RootContext.getXID());
//扣減張三的金額
accountInfoMapper.updateAccountBalance(accountNo,amount *-1);
//調(diào)用李四微服務(wù)堵未,轉(zhuǎn)賬
String transfer = bank2Client.transfer(amount);
if("fallback".equals(transfer)){
//調(diào)用李四微服務(wù)異常
throw new RuntimeException("調(diào)用李四微服務(wù)異常");
}
if(amount == 2){
//人為制造異常
throw new RuntimeException("bank1 make exception..");
}
}
}
- 3腋舌、Bank2Client接口的FeignClient
@FeignClient(value="seata-bank2")
public interface Bank2Client {
//遠(yuǎn)程調(diào)用微服務(wù)
@GetMapping("/bank2/transfer/{amount}")
public String transfer(@PathVariable("amount")Long amount);
}
其他微服務(wù)按此配置即可。
github源碼地址:https://github.com/jjhyb/distributed-transaction
參考:
https://github.com/seata/seata
http://classinstance.cn/detail/73.html
http://seata.io/en-us/docs/ops/deploy-server.html
https://www.cnblogs.com/h--d/p/12994365.html
https://developer.aliyun.com/article/768872
https://www.freesion.com/article/5542273585/
https://blog.csdn.net/u013058742/article/details/104063203
https://blog.csdn.net/sinat_38670641/article/details/108237920