SpringCloud Alibaba Seata (收藏版)
一、簡介
官網(wǎng)地址: http://seata.io/zh-cn/
1,概念
Seata是一款開源的分布式事務(wù)解決方案,致力于在微服務(wù)架構(gòu)在提供高性能和簡單一樣的分布式事務(wù)服務(wù)。
2,處理過程
Transaction ID XID:全局唯一的事務(wù)ID
Transaction Coordinator(TC) :維護全局和分支事務(wù)的狀態(tài),驅(qū)動全局事務(wù)提交或回滾。
Transaction Manager™ :定義全局事務(wù)的范圍:開始全局事務(wù)、提交或回滾全局事務(wù)。
Resource Manager(RM) :管理分支事務(wù)處理的資源,與TC交談以注冊分支事務(wù)和報告分支事務(wù)的狀態(tài),并驅(qū)動分支事務(wù)提交或回滾。

- TM向TC申請開啟一個全局事務(wù),全局事務(wù)創(chuàng)建成功并生成一個全局唯一的XID
- XID在微服務(wù)調(diào)用鏈路的上下文中傳播
- RM向TC注冊分支事務(wù),將其納入XID對應(yīng)全局事務(wù)的管轄
- TM向TC發(fā)起針對XID的全局提交或回滾決議
- TC調(diào)度XID下管轄的全部分支事務(wù)完成提交或回滾請求
二、Seata-Server的安裝
1,下載
http://seata.io/zh-cn/blog/download.html 選擇指定版本下載(我這里用的是0.9.0)
2,修改配置文件
修改seata/conf/file.conf
#將service中修改group
vgroup_mapping.my_test_tx_group = "my_group"
#將store模塊修改為db并修改數(shù)據(jù)連接,將conf目錄下的db_store.sql文件導入到數(shù)據(jù)庫中
mode = "db"
db {
datasource = "dbcp"
db-type = "mysql"
driver-class-name = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://127.0.0.1:3306/seata"
user = "root"
password = "123456"
}
修改seata/conf/registry.conf
registry {
type = "nacos"
nacos {
serverAddr = "localhost:8848"
namespace = ""
cluster = "default"
}
三、Seata的應(yīng)用
1,訂單服務(wù)
源碼: seata-order-service2001
a,配置pom
<!--nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--seata-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<exclusions>
<exclusion>
<artifactId>seata-all</artifactId>
<groupId>io.seata</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
<version>0.9.0</version>
</dependency>
<!--feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--web-actuator-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--mysql-druid-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
b,配置yaml
server:
port: 2001
spring:
application:
name: seata-order-service
cloud:
alibaba:
seata:
#自定義事務(wù)組名稱需要與seata-server中的對應(yīng)
tx-service-group: my_group
nacos:
discovery:
server-addr: localhost:8848
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/seata_order
username: root
password: 123456
feign:
hystrix:
enabled: false
logging:
level:
io:
seata: info
mybatis:
mapperLocations: classpath:mapper/*.xml
c,添加file.conf(與seata-server配置相同)
transport {
# tcp udt unix-domain-socket
type = "TCP"
#NIO NATIVE
server = "NIO"
#enable heartbeat
heartbeat = true
#thread factory for netty
thread-factory {
boss-thread-prefix = "NettyBoss"
worker-thread-prefix = "NettyServerNIOWorker"
server-executor-thread-prefix = "NettyServerBizHandler"
share-boss-worker = false
client-selector-thread-prefix = "NettyClientSelector"
client-selector-thread-size = 1
client-worker-thread-prefix = "NettyClientWorkerThread"
# netty boss thread size,will not be used for UDT
boss-thread-size = 1
#auto default pin or 8
worker-thread-size = 8
}
shutdown {
# when destroy server, wait seconds
wait = 3
}
serialization = "seata"
compressor = "none"
}
service {
vgroup_mapping.my_group = "default"
default.grouplist = "127.0.0.1:8091"
enableDegrade = false
disable = false
max.commit.retry.timeout = "-1"
max.rollback.retry.timeout = "-1"
disableGlobalTransaction = false
}
client {
async.commit.buffer.limit = 10000
lock {
retry.internal = 10
retry.times = 30
}
report.retry.count = 5
tm.commit.retry.count = 1
tm.rollback.retry.count = 1
}
## transaction log store
store {
## store mode: file、db
mode = "db"
## file store
file {
dir = "sessionStore"
# branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
max-branch-session-size = 16384
# globe session size , if exceeded throws exceptions
max-global-session-size = 512
# file buffer size , if exceeded allocate new buffer
file-write-buffer-cache-size = 16384
# when recover batch read size
session.reload.read_size = 100
# async, sync
flush-disk-mode = async
}
## database store
db {
## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
datasource = "dbcp"
## mysql/oracle/h2/oceanbase etc.
db-type = "mysql"
driver-class-name = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://127.0.0.1:3306/seata"
user = "root"
password = "123456"
min-conn = 1
max-conn = 3
global.table = "global_table"
branch.table = "branch_table"
lock-table = "lock_table"
query-limit = 100
}
}
lock {
## the lock store mode: local、remote
mode = "remote"
local {
## store locks in user's database
}
remote {
## store locks in the seata's server
}
}
recovery {
#schedule committing retry period in milliseconds
committing-retry-period = 1000
#schedule asyn committing retry period in milliseconds
asyn-committing-retry-period = 1000
#schedule rollbacking retry period in milliseconds
rollbacking-retry-period = 1000
#schedule timeout retry period in milliseconds
timeout-retry-period = 1000
}
transaction {
undo.data.validation = true
undo.log.serialization = "jackson"
undo.log.save.days = 7
#schedule delete expired undo_log in milliseconds
undo.log.delete.period = 86400000
undo.log.table = "undo_log"
}
## metrics settings
metrics {
enabled = false
registry-type = "compact"
# multi exporters use comma divided
exporter-list = "prometheus"
exporter-prometheus-port = 9898
}
support {
## spring
spring {
# auto proxy the DataSource bean
datasource.autoproxy = false
}
}
d,添加registry.conf(與seata-server的配置相同)
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "nacos"
nacos {
serverAddr = "localhost:8848"
namespace = ""
cluster = "default"
}
eureka {
serviceUrl = "http://localhost:8761/eureka"
application = "default"
weight = "1"
}
redis {
serverAddr = "localhost:6379"
db = "0"
}
zk {
cluster = "default"
serverAddr = "127.0.0.1:2181"
session.timeout = 6000
connect.timeout = 2000
}
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 = "file"
nacos {
serverAddr = "localhost"
namespace = ""
}
consul {
serverAddr = "127.0.0.1:8500"
}
apollo {
app.id = "seata-server"
apollo.meta = "http://192.168.1.204:8801"
}
zk {
serverAddr = "127.0.0.1:2181"
session.timeout = 6000
connect.timeout = 2000
}
etcd3 {
serverAddr = "http://localhost:2379"
}
file {
name = "file.conf"
}
}
e,fegin調(diào)用(這里以其中一個account為例)
@FeignClient(value = "seata-account-service")
public interface AccountService {
@RequestMapping("/account/decrease")
public CommonResult decrease(@RequestParam("userId") Long userId, @RequestParam("money") BigDecimal money);
}
f,事務(wù)service
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
OrderDao orderDao;
@Autowired
AccountService accountService;
@Autowired
StorageService storageService;
@Override
@GlobalTransactional(name = "my-order-test",rollbackFor = Exception.class) //加注解使用全局的事務(wù),name 為事務(wù)名稱不重復(fù)就行
public Long create(Order order) {
log.info("=========================下訂單,開始");
orderDao.create(order);
log.info("=========================下訂單,完成");
log.info("=========================減庫存,開始");
storageService.decrease(order.getProductId(), order.getCount());
log.info("=========================減庫存,完成");
log.info("=========================減積分,開始");
accountService.decrease(order.getUserId(), order.getMoney());
log.info("=========================減積分,完成");
log.info("=========================訂單狀態(tài)修改,開始");
orderDao.update(order.getId(),1);
log.info("=========================訂單狀態(tài)修改,完成");
return order.getId();
}
}
g,啟動類
2,庫存服務(wù)
源碼: seata-storage-service2002
與訂單服務(wù)中的a,b,c,d,g配置步驟相同
3,賬戶服務(wù)
源碼: seata-account-service2003
與庫存服務(wù)的配置步驟相同
四、Seata的原理解析
參考文檔: http://seata.io/zh-cn/docs/overview/what-is-seata.html
1,AT模式 一階段
1,解析SQL語義,找到"業(yè)務(wù)SQL"要更新的業(yè)務(wù)數(shù)據(jù),在業(yè)務(wù)數(shù)據(jù)被更新前,將其保存成"before image"
2,執(zhí)行"業(yè)務(wù)SQL"更新業(yè)務(wù)數(shù)據(jù),在業(yè)務(wù)數(shù)更新之后
3,將其保存成"after image",最后生成行鎖。
以上操作全部在一個數(shù)據(jù)庫事務(wù)內(nèi)完成,這樣保證了一階段操作的原子性。

二階段提交
因為"業(yè)務(wù)SQL"在一階段已經(jīng)提交至數(shù)據(jù)庫,所以seata框架只需 將一階段保存的快照數(shù)據(jù)和行鎖刪掉 ,完成數(shù)據(jù)清理即可。

二階段回滾
二階段如果是回滾的話,seata就需要回滾一階段已經(jīng)執(zhí)行的"業(yè)務(wù)SQL",還原業(yè)務(wù)數(shù)據(jù)。
回滾的方式便是用"before image"還原業(yè)務(wù)數(shù)據(jù);但在還原前要首先校驗臟寫,對比"數(shù)據(jù)庫當前業(yè)務(wù)數(shù)據(jù)"和"after image"
如果兩份數(shù)據(jù)完全一致就說明沒有臟寫,可以還原業(yè)務(wù)數(shù)據(jù),如果不一致就說明有臟寫,出現(xiàn)臟寫就需要轉(zhuǎn)人工處理。

到此這篇關(guān)于SpringCloud Alibaba Seata 收藏來了的文章就介紹到這了,更多相關(guān)SpringCloud Alibaba Seata 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot3 響應(yīng)式網(wǎng)絡(luò)請求客戶端的實現(xiàn)
本文主要介紹了SpringBoot3 響應(yīng)式網(wǎng)絡(luò)請求客戶端的實現(xiàn),文章詳細闡述了如何使用SpringBoot3的網(wǎng)絡(luò)請求客戶端進行HTTP請求和處理響應(yīng),并提供了示例代碼和說明,具有一定的參考價值,感興趣的可以了解一下2023-08-08
mybatis的坑-integer類型為0的數(shù)據(jù)if?test失效問題
這篇文章主要介紹了mybatis的坑-integer類型為0的數(shù)據(jù)if?test失效問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
SpringBoot學習系列之MyBatis Plus整合封裝的實例詳解
MyBatis-Plus是一款MyBatis的增強工具(簡稱MP),為簡化開發(fā)、提高效率,這篇文章給大家介紹MyBatis Plus整合封裝的實例詳解,感興趣的朋友跟隨小編一起看看吧2020-08-08
帶你了解Java數(shù)據(jù)結(jié)構(gòu)和算法之遞歸
這篇文章主要為大家介紹了Java數(shù)據(jù)結(jié)構(gòu)和算法之遞歸,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-01-01
IDEA2020 Plugins不能用的解決辦法及Plugins 搜索不了插件的問題
這篇文章主要介紹了IDEA2020 Plugins不能用的解決辦法,文中給大家介紹了Intellij IDEA 2020.1 的Plugins 搜索不了插件,連接超時的問題,本文給大家介紹的非常詳細,需要的朋友可以參考下2020-06-06
Spring MVC請求參數(shù)與響應(yīng)結(jié)果全局加密和解密詳解
這篇文章主要給大家介紹了關(guān)于Spring MVC請求參數(shù)與響應(yīng)結(jié)果全局加密和解密的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-08-08

