1. 程式人生 > 程式設計 >詳解SpringCloud-Alibaba-Seata分散式事務

詳解SpringCloud-Alibaba-Seata分散式事務

前言
Seata 是一款阿里巴巴開源的分散式事務解決方案,致力於在微服務架構下提供高效能和簡單易用的分散式事務服務。

Seata 是一款開源的分散式事務解決方案,致力於提供高效能和簡單易用的分散式事務服務。Seata 將為使用者提供了 AT、TCC、SAGA 和 XA 事務模式,為使用者打造一站式的分散式解決方案。

術語

TC (Transaction Coordinator) - 事務協調者
維護全域性和分支事務的狀態,驅動全域性事務提交或回滾。

TM (Transaction Manager) - 事務管理器
定義全域性事務的範圍:開始全域性事務、提交或回滾全域性事務。

RM (Resource Manager) - 資源管理器

管理分支事務處理的資源,與TC交談以註冊分支事務和報告分支事務的狀態,並驅動分支事務提交或回滾。
1.
XID:全域性唯一事務ID
TC:事務協調器,維護全域性事務的執行狀態,負責協調並驅動全域性的提交或回滾
TM:控制全域性事務的邊界,負責開啟一全域性事務,並最終發起全域性提交或者回滾的決議
RM:控制分支事務,負責分支註冊,狀態彙報,並接受事務協調的指令,驅動分支的事務提交或者回滾
2.
TM向TC申請開啟一個全域性的事務,全域性事務建立成功並生成一個唯一的全域性ID,XID在微服務呼叫鏈路的上下文中傳播
RM向TC註冊分支事務,將其納入XID對應事務的 管轄
TM向TC發起針對XID的全域性提交或者回滾
TC排程XID下管轄的全部分支事務完成提交或者回滾

在這裡插入圖片描述

官方文件https://seata.io/zh-cn/docs/overview/what-is-seata.html

示例 win版
下載安裝
https://github.com/seata/seata/releases/tag/v1.3.0

在這裡插入圖片描述

下載好的包解壓 解壓
在這裡插入圖片描述
配置 seata
開啟\seata\seata\conf 下編輯 file.conf檔案
在這裡插入圖片描述
修改資料庫模式
在這裡插入圖片描述
file.conf 檔案修改連結資料的 資訊
修改本地mysql的地址與賬號密碼
在這裡插入圖片描述
file.conf 中的service也沒有手動新增
vgroup_mapping.my_test_tx_group = “default”

default任意定義名字

service {
 #transaction service group mapping
 #修改,可不改,my_test_tx_grou。
 vgroup_mapping.my_test_tx_group = "default"
 #only support when registry.type=file,please don't set multiple addresses
 # 此服務的地址
 default.grouplist = "127.0.0.1:8091"
 #disable seata
 disableGlobalTransaction = false
}

建立資料庫 執行官方給的額Sql檔案
我草!沒有sql指令碼, 0.9版本有sql指令碼
網上找了一個

DROP TABLE IF EXISTS `branch_table`;
CREATE TABLE `branch_table` (
 `branch_id` bigint(20) NOT NULL,`xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,`transaction_id` bigint(20) NULL DEFAULT NULL,`resource_group_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`resource_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`branch_type` varchar(8) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`status` tinyint(4) NULL DEFAULT NULL,`client_id` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`application_data` varchar(2000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`gmt_create` datetime(6) NULL DEFAULT NULL,`gmt_modified` datetime(6) NULL DEFAULT NULL,PRIMARY KEY (`branch_id`) USING BTREE,INDEX `idx_xid`(`xid`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of branch_table
-- ----------------------------

-- ----------------------------
-- Table structure for global_table
-- ----------------------------
DROP TABLE IF EXISTS `global_table`;
CREATE TABLE `global_table` (
 `xid` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,`status` tinyint(4) NOT NULL,`application_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`transaction_service_group` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`transaction_name` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`timeout` int(11) NULL DEFAULT NULL,`begin_time` bigint(20) NULL DEFAULT NULL,`gmt_create` datetime(0) NULL DEFAULT NULL,`gmt_modified` datetime(0) NULL DEFAULT NULL,PRIMARY KEY (`xid`) USING BTREE,INDEX `idx_gmt_modified_status`(`gmt_modified`,`status`) USING BTREE,INDEX `idx_transaction_id`(`transaction_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of global_table
-- ----------------------------

-- ----------------------------
-- Table structure for lock_table
-- ----------------------------
DROP TABLE IF EXISTS `lock_table`;
CREATE TABLE `lock_table` (
 `row_key` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,`xid` varchar(96) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`branch_id` bigint(20) NOT NULL,`table_name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`pk` varchar(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,PRIMARY KEY (`row_key`) USING BTREE,INDEX `idx_branch_id`(`branch_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of lock_table
-- ----------------------------

-- ----------------------------
-- Table structure for undo_log
-- ----------------------------
DROP TABLE IF EXISTS `undo_log`;
CREATE TABLE `undo_log` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,`xid` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,`context` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,`rollback_info` longblob NOT NULL,`log_status` int(11) NOT NULL,`log_created` datetime(0) NOT NULL,`log_modified` datetime(0) NOT NULL,`ext` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE,UNIQUE INDEX `ux_undo_log`(`xid`,`branch_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

修改conf資料夾下 registry.conf ,
seata 支援註冊nacos 、eureka、redis、zk、consul、etcd3、sofa
本地的nacos的地址
在這裡插入圖片描述
改完配置檔案儲存 測試
啟動ncos 在啟動seata
在這裡插入圖片描述
Seata 下bin目錄在這裡插入圖片描述

在這裡插入圖片描述
在這裡插入圖片描述
程式碼示例
pom

<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>1.3.0</version>
  </dependency>

使用庫下建立`undo_log表

drop table `undo_log`;
CREATE TABLE `undo_log` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT,`xid` varchar(100) NOT NULL,`context` varchar(128) NOT NULL,`log_created` datetime NOT NULL,`log_modified` datetime NOT NULL,`ext` varchar(100) DEFAULT NULL,PRIMARY KEY (`id`),UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

yml

server:
 port: 2001
 
spring:
 application:
 name: seata-order-service
 cloud:
 alibaba:
  seata:
  #自定義事務組名稱需要與seata-server中的對應
  tx-service-group: default
 nacos:
  discovery:
  server-addr: localhost:8848
 datasource:
 driver-class-name: com.mysql.jdbc.Driver
 url: jdbc:mysql://localhost:3306/seata_order
 username: root
 password: root
 
feign:
 hystrix:
 enabled: false
 
logging:
 level:
 io:
  seata: info
 
mybatis:
 mapperLocations: classpath:mapper/*.xml

file.conf

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.fsp_tx_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 = "root"
 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
 }
}

registry.conf

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"
 }
}
@GlobalTransactional(name = "tang,rollbackFor = Exception.class)開啟全域性事物
@Override
 @GlobalTransactional(name = "tang,rollbackFor = Exception.class)
 public void create(Providers providers ){
  test1Mapper.add(providers);
  test2Mapper.add(providers)
  }

到此這篇關於SpringCloud-Alibaba-Seata分散式事務的文章就介紹到這了,更多相關SpringCloud-Alibaba-Seata分散式事務內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!