這裏只講解Seata的安裝與配置,由於Seata在1.0.0版本之後配置有很大改變,有很多坑,所以在此說明一下
Windows與Linux版本的下載地址:https://seata.io/zh-cn/blog/download.html
本案例源碼下載:
https://download.csdn.net/download/weixin_44790046/12553839
一、Windows安裝配置Seata
下載完成後解壓即可
1、修改seata-server-1.2.0\seata\conf\file.conf
文件
#修改內容如下
## transaction log store, only used in seata-server
store {
## store mode: file、db
mode = "db" #!!!!!!!!!這裏改爲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://192.168.200.131:3306/seata" #!!!!!!!!!你的msyql
user = "root" #!!!!!!!!!用戶名
password = "362623" #!!!!!!!!!密碼
minConn = 5
maxConn = 30
globalTable = "global_table"
branchTable = "branch_table"
lockTable = "lock_table"
queryLimit = 100
maxWait = 5000
}
}
1、修改seata-server-1.2.0\seata\conf\registry.conf
文件
#修改內容如下
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "nacos" #!!!!!!!!!改爲nacos
nacos {
application = "seata-server"
serverAddr = "192.168.200.199" #!!!!!!!!!註冊中心地址
namespace = ""
cluster = "default"
username = "nacos" #!!!!!!!!!用戶名
password = "nacos" #!!!!!!!!!密碼
}
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
nacos {
serverAddr = "192.168.200.199" #!!!!!!!!!配置中心地址
namespace = ""
group = "SEATA_GROUP"
username = "nacos" #!!!!!!!!!用戶名
password = "nacos" #!!!!!!!!!密碼
}
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、首先啓動Nacos服務,然後再啓動Seata,查看nacos服務註冊中心是否註冊上了Seata
二、搭建Seata運行環境
1、在你的mysql數據庫中創建名爲seata的庫,並創建以下數據表
-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data
CREATE TABLE IF NOT EXISTS `global_table`
(
`xid` VARCHAR(128) NOT NULL,
`transaction_id` BIGINT,
`status` TINYINT NOT NULL,
`application_id` VARCHAR(32),
`transaction_service_group` VARCHAR(32),
`transaction_name` VARCHAR(128),
`timeout` INT,
`begin_time` BIGINT,
`application_data` VARCHAR(2000),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`xid`),
KEY `idx_gmt_modified_status` (`gmt_modified`, `status`),
KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
-- the table to store BranchSession data
CREATE TABLE IF NOT EXISTS `branch_table`
(
`branch_id` BIGINT NOT NULL,
`xid` VARCHAR(128) NOT NULL,
`transaction_id` BIGINT,
`resource_group_id` VARCHAR(32),
`resource_id` VARCHAR(256),
`branch_type` VARCHAR(8),
`status` TINYINT,
`client_id` VARCHAR(64),
`application_data` VARCHAR(2000),
`gmt_create` DATETIME(6),
`gmt_modified` DATETIME(6),
PRIMARY KEY (`branch_id`),
KEY `idx_xid` (`xid`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(
`row_key` VARCHAR(128) NOT NULL,
`xid` VARCHAR(96),
`transaction_id` BIGINT,
`branch_id` BIGINT NOT NULL,
`resource_id` VARCHAR(256),
`table_name` VARCHAR(32),
`pk` VARCHAR(36),
`gmt_create` DATETIME,
`gmt_modified` DATETIME,
PRIMARY KEY (`row_key`),
KEY `idx_branch_id` (`branch_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8;
2、要在參與全局事務的每個數據庫中都加入undo_log
這張表
-- for AT mode you must to init this sql for you business database. the seata server not need it.
CREATE TABLE IF NOT EXISTS `undo_log`
(
`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'increment id',
`branch_id` BIGINT(20) NOT NULL COMMENT 'branch transaction id',
`xid` VARCHAR(100) NOT NULL COMMENT 'global transaction id',
`context` VARCHAR(128) NOT NULL COMMENT 'undo_log context,such as serialization',
`rollback_info` LONGBLOB NOT NULL COMMENT 'rollback info',
`log_status` INT(11) NOT NULL COMMENT '0:normal status,1:defense status',
`log_created` DATETIME NOT NULL COMMENT 'create datetime',
`log_modified` DATETIME NOT NULL COMMENT 'modify datetime',
PRIMARY KEY (`id`),
UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = InnoDB
AUTO_INCREMENT = 1
DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';
如我測試用例使用的3個數據庫
3、從官方github倉庫拿到參考配置做修改 https://github.com/seata/seata/tree/develop/script/client/spring
加到你項目的application.yml中。
seata:
enabled: true
application-id: applicationName
tx-service-group: my_test_tx_group
enable-auto-data-source-proxy: true
config:
type: nacos
nacos:
namespace:
serverAddr: 127.0.0.1:8848
group: SEATA_GROUP
userName: "nacos"
password: "nacos"
registry:
type: nacos
nacos:
application: seata-server
server-addr: 127.0.0.1:8848
namespace:
userName: "nacos"
password: "nacos"
4、由於Seata1.2.0支持從Nacos讀取配置,所以我們還需要一個bootstrap.yml
讀取配置信息
#Nacos同springcloud-config-樣, 在項目初始化時,要保證先從配置中心進行配置拉取,拉取配置之後,才能保證項目的正常啓動。
#springboot中配置文件的加載是存在優先級順序的,bootstrap優先級高於application
#當前服務端口號
server:
port: 2002
spring:
application:
name: seata-storage-service #當前服務名稱
main:
allow-bean-definition-overriding: true
cloud:
loadbalancer:
retry:
enabled: false
nacos:
discovery:
server-addr: 192.168.200.199 #通過虛擬IP訪問Nginx主服務器,然後反向代理到其中一臺nacos註冊中心
config:
server-addr: 192.168.200.199 #通過虛擬IP訪問Nginx主服務器,然後反向代理到其中一臺nacos配置中心
#設置feign客戶端超時時間(OpenFeign默認支持ribbon)
ribbon:
ReadTimeout: 5000 #指的是建立連接所用的時間,適用於網絡狀況正常的情況下,兩端連接所用的時間
connectTimeout: 5000 #指的是建立連接後從服務器讀取到可用資源所用的時間
5、項目pom文件
<dependencies>
<!-- nacos 作爲服務註冊中心 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- nacos 作爲配置中心 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!--SpringCloud集成OpenFeign服務調用-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--SpringCloudAlibaba的seata分佈式事務管理-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-seata</artifactId>
<exclusions>
<exclusion>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--指定與安裝的seata版本一致,重要!-->
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<!-- SpringBoot框架集成web項目起步依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot健康監控功能起步依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--mybatis集成SpringBoot起步依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!--阿里Druid連接池集成SpringBoot起步依賴-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
<!--MySQL驅動依賴-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!--熱部署依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--提供一系列方便生成get、set方法等的註解依賴-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<scope>provided</scope>
</dependency>
<!-- SpringBoot單元測試依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
6、將Seata項目克隆或下載到本地 https://github.com/seata/seata
克隆完成後進入\seata\script\config-center目錄修改config.txt爲以下內容。
service.vgroupMapping.my_test_tx_group=default
store.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.jdbc.Driver
store.db.url=jdbc:mysql://192.168.200.131:3306/seata?useUnicode=true #!!!!!!!!MySQL的URL
store.db.user=username #!!!!!!!!!用戶名
store.db.password=password #!!!!!!!!!密碼
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
運行倉庫中提供的nacos腳本,將以上信息提交到nacos控制檯,如果有需要更改,可直接通過控制檯更改
注意:
如果你的nacos地址不是本機,需要修改腳本nacos-config.sh
,他是默認使用本機nacos的,修改地方如下
導入完成後,nacos註冊中心中,配置列表如下即可
三、測試事務是否成功
主要業務邏輯,使用Seata的全局事務只需要在方法上加
@GlobalTransactional
註解即可,使用很簡單,但是配置很繁瑣,還很容易錯
剛進入事務還沒以有執行業務代碼時,
生成了一個全局唯一的Xid
global_table數據表裏也多了一條記錄
創建訂單的微服務執行
首先訂單數據庫的undo_log表生成一條記錄,同時branch_table表中也會添加一行當前服務的記錄
訂單表生成記錄
執行到下面扣減餘額時發生異常,事務就會回滾
四、搭建高可用的Seata
啓動另一個Seata
seata-server.bat -p 8092
五、常見問題解析
1.xid未傳遞
- 一般常見於springcloud的用戶,請注意是否只引入了seata-all或者seata-spring-boot-starter.如果是,請換爲本文介紹給springcloud的依賴即可.
- 如果是自己實現了WebMvcConfigurer,那麼請參考com.alibaba.cloud.seata.web.SeataHandlerInterceptorConfiguration#addInterceptors把xid傳遞攔截器加入到你的攔截鏈路中
2.數據源未代理
一般分爲2種情況
- 數據源自己創建後,代理數據源的beanname爲DataSourceProxy而不是dataSource,導致sqlsessionfactory注入的並不是被代理後的.
- 如果是已經開啓了自動代理的用戶,請確認是否手寫了sqlsessionfactory此時注入的DataSource並未顯示是DataSourceproxy代理的情況,請進行調整,保證注入是代理的數據源.
3.事務分組配置出錯導致無法找到tc
一般由於對事務分組的理解出現偏差導致的,請仔細閱讀官網的參數配置中的介紹.
TM端: seata.tx-service-group=自定分組名, seata.service.vgroup-mapping(配置中心中是叫:service.vgroupMapping).自定分組名=服務端註冊中心配置的cluster/application的值
拿nacos舉例子
比如我Seata的registry.conf
配置文件中nacos的cluster
nacos {
application = "seata-server"
serverAddr = "localhost"
namespace = ""
cluster = "testCluster"
username = "nacos"
password = "nacos"
}
application配置文件中設置的事務分組爲
seata:
tx-service-group: test
那麼nacos中需要配置的事務分組的key、value爲
service.vgroupMapping.test=testCluster
4.Global lock acquire failed
一般這種情況也是分爲兩種
- 常見的就是並沒有對select語句進行forupdate,如果你不開啓forupdate,seata默認是遇到併發性競爭鎖並不會去嘗試重試,導致拿不到lock當前事務進行回滾.不影響一致性,如果你想沒forupdate也開啓競爭鎖client.rm.lock.retryPolicyBranchRollbackOnConflict設置爲false(有死鎖風險)
- 還有一種就是由於大併發下對同一個數據併發操作時,前一個事務還未提交,後續的事務一直在等待,而seata默認的超時週期爲300ms,此時超時後就會拋出Globallock acquire failed,當前事務進行回滾,如果你想保住競爭鎖的週期足夠長,請更改client.rm.lock.retryTimes和client.rm.lock.retryInterval來保證週期的合理性.
5.Could not found global transaction xid
-
一般出現這個提示與服務重試及超時有關,比如A->B此時A調B超時,A默認是重試的,B等於被調了2遍,第二次被調用的B進行了響應,A發起者接收到結果後進行了提交/回滾,這次超時的B因爲網絡問題現在才被調用,他也收到了一樣的全局事務id,進行業務處理,直到註冊分支,此時全局事務已經被提交/回滾,導致當前超時的分支事務B無法註冊上.
-
這種問題一般保證你的業務不會去超時重試,如果你需要,請確認全局事務狀態,做好冪等,反正已經做過的處理重複操作.
六、分佈式事務的執行流程
- TM開啓分佈式事務(TM向TC註冊全局事務記錄)
- 換業務場景,編排數據庫,服務等事務內資源(RM向TC彙報資源準備狀態)
- TM結束分佈式事務,事務一階段結束(TM通知TC提交/回滾分佈式事務)
- TC彙總事務信息,決定分佈式事務是提交還是回滾
- TC通知所有RM提交/回滾資源,事務二階段結束。
七、AT模式如何做到對業務的無侵入
在一階段, Seata 會攔截“業務SQL”
-
1解析SQL語義,找到“業務SQL"要更新的業務數據,在業務數據被更新前,將其保存成"before image"
-
2執行“業務SQL"更新業務數據,在業務數據更新之後, 3其保存成"after image” ,最後生成行鎖。
以上操作全部在一個數據庫事務內完成,這樣保證了一階段操作的原子性。
如果以上不出現異常就會進行二階段提交
- 二階段如是順利提交的話,
“業務SQL"在一階段已經提交至數據庫,所以Seata框架只需將一階段保存的快照數據和行鎖刪掉, 完成數據清理即可。
出現異常則進行第三階段回滾
- 二階段如果是回滾的話,Seata就需要回滾一階段已經執行的“業務SQL" ,還原業務數據。
- 回滾方式便是用"before image"還原業務數據;但在還原前要首先要校驗髒寫,對比”數據庫當前業務數據”和” after image”
- 如果兩份數據完全一致就說明沒有髒寫, 可以還原業務數據,如果不一致就說明有髒寫,出現髒寫就需要轉人工處理。