Spring Cloud Nacos集成Seata2.0 AT模式
以CentOS 7為例,介紹Spring Cloud Nacos集成Seata2.0 AT模式的流程。分成兩個步驟:1.安裝配置seata-server、2.項目集成seata-client
一、下載seata-server安裝包
根據自己的操作系統選擇要下載的安裝包格式:下載地址
二、解壓安裝
將安裝包放到指定目錄(以/usr/soft/seata為例)
解壓,重命名
tar -zxvf seata-server-2.0.0.tar.gz
mv seata seata-server-2.0.0
創建生成環境和開發環境目錄:
mkdir dev
mkdir prod
將解壓后的seata-server-2.0.0拷貝到dev目錄下,進入dev目錄下:
cp seata-server-2.0.0 -a dev/
cd dev
三、修改seata配置
修改conf目錄下的application.yml:
server:port: 7091spring:application:name: seata-serverlogging:config: classpath:logback-spring.xmlfile:path: ${log.home:${user.home}/logs/seata}extend:logstash-appender:destination: 127.0.0.1:4560kafka-appender:bootstrap-servers: 127.0.0.1:9092topic: logback_to_logstashconsole:user:username: seatapassword: seata# 這里是主要的配置文件
seata:config:# support: nacos, consul, apollo, zk, etcd3type: nacosnacos:server-addr: 127.0.0.1:8848username: nacospassword: nacos# 如果在nacos上添加了命名空間,則配置命名空間IDnamespace: fba13bcb-xxxxx-c9a0e # dev# 配置分組group: SEATA_GROUPcontext-path:##if use MSE Nacos with auth, mutex with username/password attribute#access-key:#secret-key:data-id: seataServer.propertiesregistry:# support: nacos 、 eureka 、 redis 、 zk 、 consul 、 etcd3 、 sofatype: nacospreferred-networks: 30.240.*nacos:application: seata-serverserver-addr: 127.0.0.1:8848username: nacospassword: nacosnamespace: fba13bcb-xxxx-c9a0e # devgroup: DEFAULT_GROUPcluster: defaultcontext-path:##if use MSE Nacos with auth, mutex with username/password attribute#access-key:#secret-key:server:service-port: 8091 #If not configured, the default is '${server.port} + 1000'max-commit-retry-timeout: -1max-rollback-retry-timeout: -1rollback-retry-timeout-unlock-enable: falseenable-check-auth: trueenable-parallel-request-handle: trueenable-parallel-handle-branch: falseretry-dead-threshold: 130000xaer-nota-retry-timeout: 60000enableParallelRequestHandle: truerecovery:committing-retry-period: 1000async-committing-retry-period: 1000rollbacking-retry-period: 1000timeout-retry-period: 1000undo:log-save-days: 7log-delete-period: 86400000session:branch-async-queue-size: 5000 #branch async remove queue sizeenable-branch-async-remove: false #enable to asynchronous remove branchSessionstore:# support: file 、 db 、 redis 、 raftmode: dbsession:mode: dblock:mode: dbdb:datasource: druiddb-type: mysqldriver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/mingink-seata?rewriteBatchedStatements=true&&useSSL=falseuser: rootpassword: rootmin-conn: 10max-conn: 100global-table: global_tablebranch-table: branch_tablelock-table: lock_tabledistributed-lock-table: distributed_lockquery-limit: 1000max-wait: 5000metrics:enabled: falseregistry-type: compactexporter-list: prometheusexporter-prometheus-port: 9898transport:rpc-tc-request-timeout: 15000enable-tc-server-batch-send-response: falseshutdown:wait: 3thread-factory:boss-thread-prefix: NettyBossworker-thread-prefix: NettyServerNIOWorkerboss-thread-size: 1security:secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017tokenValidityInMilliseconds: 1800000ignore:urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.jpeg,/**/*.ico,/api/v1/auth/login,/metadata/v1/**
為了讓tc服務的集群可以共享配置,我們選擇了nacos作為統一配置中心。因此服務端配置文件seataServer.properties文件需要在nacos中配好。在nacos的dev環境中創建seataServer的配置文件:
配置內容如下:
# 數據存儲方式,db代表數據庫
store.mode=db
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/mingink-seata?useUnicode=true&rewriteBatchedStatements=true&serverTimezone=GMT%2B8
store.db.user=root
store.db.password=root
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.distributedLockTable=distributed_lock
store.db.queryLimit=100
store.db.lockTable=lock_table
store.db.distributedLockTable=distributed_lock
store.db.maxWait=5000
# 事務、日志等配置
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
server.undo.logSaveDays=7
server.undo.logDeletePeriod=86400000# 客戶端與服務端傳輸方式
transport.serialization=seata
transport.compressor=none
# 關閉metrics功能,提高性能
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898
四、創建數據庫表
特別注意:tc服務在管理分布式事務時,需要記錄事務相關數據到數據庫中,這些表主要記錄全局事務、分支事務、全局鎖信息,你需要提前創建好這些表。
新建一個名為mingink-seata的數據庫(數據庫名可以自定義,注意與上面配置對應上):
-- -------------------------------- The script used when storeMode is 'db' --------------------------------
-- the table to store GlobalSession data(可以在/script/server/db/mysql.sql找到對應版本的sql文件)
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_status_gmt_modified` (`status` , `gmt_modified`),KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDBDEFAULT CHARSET = utf8mb4;-- 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 = InnoDBDEFAULT CHARSET = utf8mb4;-- the table to store lock data
CREATE TABLE IF NOT EXISTS `lock_table`
(`row_key` VARCHAR(128) NOT NULL,`xid` VARCHAR(128),`transaction_id` BIGINT,`branch_id` BIGINT NOT NULL,`resource_id` VARCHAR(256),`table_name` VARCHAR(32),`pk` VARCHAR(36),`status` TINYINT NOT NULL DEFAULT '0' COMMENT '0:locked ,1:rollbacking',`gmt_create` DATETIME,`gmt_modified` DATETIME,PRIMARY KEY (`row_key`),KEY `idx_status` (`status`),KEY `idx_branch_id` (`branch_id`),KEY `idx_xid` (`xid`)
) ENGINE = InnoDBDEFAULT CHARSET = utf8mb4;CREATE TABLE IF NOT EXISTS `distributed_lock`
(`lock_key` CHAR(20) NOT NULL,`lock_value` VARCHAR(20) NOT NULL,`expire` BIGINT,primary key (`lock_key`)
) ENGINE = InnoDBDEFAULT CHARSET = utf8mb4;INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('AsyncCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryCommitting', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('RetryRollbacking', ' ', 0);
INSERT INTO `distributed_lock` (lock_key, lock_value, expire) VALUES ('TxTimeoutCheck', ' ', 0);
在你的項目數據庫上創建一個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`
(`branch_id` BIGINT NOT NULL COMMENT 'branch transaction id',`xid` VARCHAR(128) 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(6) NOT NULL COMMENT 'create datetime',`log_modified` DATETIME(6) NOT NULL COMMENT 'modify datetime',UNIQUE KEY `ux_undo_log` (`xid`, `branch_id`)
) ENGINE = InnoDBAUTO_INCREMENT = 1DEFAULT CHARSET = utf8 COMMENT ='AT transaction mode undo table';
五、啟動加粗樣式seata-server(TC)服務
在bin目錄下找到startup.sh文件,編輯啟動命令行:
vim startup.sh
內容如下:
./seata-server.sh -h 127.0.0.1 -p 8091
注意:如果seata-server與你的項目服務在同一臺主機可以使用127.0.0.1,如果不再同一臺主機(比如seata-server部署在ip為11.22.33.44的服務器,項目服務啟動在你的本地主機),那么這里的ip應修改為服務器的ip11.22.33.44,否則會出現本地服務找不到seata-server服務的異常
然后再bin目錄下啟動seata-server使其注冊到nacos上:
sh startup.sh
打開nacos控制面板,找到命名空間對應的服務列表:
可以發現,我們的seata-server已經成功注冊到nacos上了。在localhost:7091可以訪問seata控制臺
附:
- 重啟seata-server前需要終止之前啟動的進程,netstat -anp | grep 8091查看進程號,kill -9 pid 終止進程;
- 如果seata-server沒有注冊到nacos上,或者seata控制臺 無法打開,可能是因為你的服務器沒有開放8091和7091端口;
六、Spring Cloud整合Seata
添加Seata依賴
<!-- SpringCloud Alibaba Nacos Config --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><!-- seata模塊 --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-seata</artifactId><exclusions><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>2.0.0</version></dependency>
添加yml配置
# Seata
seata:registry: # TC服務注冊中心的配置,微服務根據這些信息去注冊中心獲取tc服務地址# 參考tc服務自己的registry.conf中的配置type: nacosnacos: # tcserver-addr: 127.0.0.1:8848username: nacospassword: nacosnamespace: ${spring.cloud.nacos.discovery.namespace}group: DEFAULT_GROUPcluster: defaultapplication: seata-server # tc服務在nacos中的服務名稱tx-service-group: seata-group # 事務組,根據這個獲取tc服務的cluster名稱service:vgroup-mapping: # 事務組與TC服務cluster的映射關系seata-group : default# 開啟數據源的代理模式data-source-proxy-mode: AT # 默認就是AT
注解
在AT模式中,使用@GlobalTransactional注解即可設置全局事務:
例如,我的MingInk-User服務中,有個register業務,它依賴于MingInk-Gorse服務的另一個業務,中間通過Open Feign進行遠程調用:
@Override@GlobalTransactionalpublic R<?> registerUser(User user) {log.info("Begin Register: 【{}】", user.getUserName());// 檢測用戶信息格式是否正確....// 插入新用戶user.setUserId(SnowFlakeFactory.getSnowFlakeFromCache().nextId()); // 雪花算法設置用戶Iduser.setUid((String.valueOf(userMapper.selectList(null).size() + 100001))); // 設置用戶Uiduser.setNickName(user.getUserName()); // 默認新用戶昵稱為用戶(賬戶)名user.setAvatar("null"); // 設置用戶默認頭像user.setBirthday(new Date());user.setStatus(0); // 默認用戶狀態為正常——0user.setLoginDate(new Date()); // 最近登錄時間user.setCreateTime(new Date()); // 當前時間user.setUpdateTime(new Date()); // 當前時間boolean isInsertSuccess = userMapper.insert(user) > 0; // 返回值int代表插入成功條數,大于0表示插入成功條數,等于0則代表插入失敗if (!isInsertSuccess) {log.info("用戶[{}]注冊失敗:", user.getUserName());return R.fail("用戶注冊失敗");}// 設置默認權限roleService.addUserRole(user.getUserId(), 3L);// 注冊Gorse UserGorseUserRequest gorseUserRequest = new GorseUserRequest();gorseUserRequest.setUserId(user.getUserId());gorseUserRequest.setLabels("[]");if (!remoteGorseService.addNewGorseUser(gorseUserRequest)) { // 這是MingInk-Gorse服務的方法// 注冊Gorse User失敗log.info("用戶[{}]注冊Gorse User失敗:", user.getUserName());return R.fail("用戶注冊失敗");}log.info("用戶[{}]注冊成功:", user.getUserName());return R.ok(null, "用戶注冊成功");}
在MingInk-Gorse服務的addNewGorseUser方法中,我們也需要給它加上@GlobalTransactional全局事務注解,讓它也能注冊到事務管理器中,使得全局事務生效:
@GlobalTransactionalpublic boolean addNewGorseUser(GorseUserRequest gorseUserRequest) {GorseUser gorseUser = new GorseUser();gorseUser.setUserId(gorseUserRequest.getUserId());gorseUser.setLabels(gorseUserRequest.getLabels());gorseUser.setComment("");gorseUser.setSubscribe("[]");return gorseUsersMapper.insert(gorseUser) > 0;}
通過上述配置,如果普通用戶注冊成功,但是Gorse用戶沒有注冊成功,會將之前執行的SQL進行回滾。
七、多seata-server部署
將dev目錄下的seata-server-2.0.0拷貝到prod目錄下:
# 進入dev目錄
cd /usr/soft/seata/dev/
# 拷貝文件
cp -a seata-server-2.0.0/ ../prod
修改prod目錄下seata配置中的服務啟動端口號以及控制臺運行端口號:
cd /usr/soft/seata/prod/seata-server-2.0.0/conf
vim application.yml
application.yml
由于我們希望新的seata-server服務運行在nacos的prod命名空間下,因此需要修改響應的namespace:
端口號發生了改變,需要同時修改bin目錄下的startup.sh:
./seata-server.sh -h 127.0.0.1 -p 8092
在nacos的prod命名空間下可以看到新啟動的seata-server服務,這樣就能跟dev開發環境區分開來了: