springcloud alibaba + seata 1.3.0 集成文档
一、seata-server端
1、下載
下載地址 http://seata.io/zh-cn/blog/download.html
由于我用nacos作為注冊(cè)中心,所有該文章以nacos為基礎(chǔ)進(jìn)行seata基礎(chǔ)配置。nacso環(huán)境搭建此處不做過(guò)多講解。
2、Nacos管理seata配置(前提nacos已安裝)
1、下載完解壓后,將以下文件放在seata文件夾
config.txt 和nacos-config.sh下載地址
https://github.com/seata/seata/tree/develop/script/config-center
https://github.com/seata/seata/tree/develop/script/config-center/nacos
- 1、config.txt,與bin目錄同級(jí)。
注意service.vgroupMapping.my_seata_group=default這行中,my_seata_group是自定義的,后面會(huì)使用到這個(gè)配置。同時(shí),本文的配置是基于mysql的方式。
transport.type=TCP transport.server=NIO transport.heartbeat=true transport.enableTmClientBatchSendRequest=false transport.enableRmClientBatchSendRequest=true transport.rpcRmRequestTimeout=5000 transport.rpcTmRequestTimeout=10000 transport.rpcTcRequestTimeout=10000 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 service.vgroupMapping.my_seata_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.tableMetaCheckerInterval=60000 client.rm.sqlParserType=druid client.rm.reportSuccessEnable=false client.rm.sagaBranchRegisterEnable=false client.rm.sagaJsonParser=fastjson client.rm.tccActionInterceptorOrder=-2147482648 client.tm.commitRetryCount=5 client.tm.rollbackRetryCount=5 client.tm.defaultGlobalTransactionTimeout=60000 client.tm.degradeCheck=false client.tm.degradeCheckAllowTimes=10 client.tm.degradeCheckPeriod=2000 client.tm.interceptorOrder=-2147482648 store.mode=db store.lock.mode=file store.session.mode=file store.publicKey= 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&rewriteBatchedStatements=true 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.maxWait=5000 store.redis.mode=single store.redis.single.host=127.0.0.1 store.redis.single.port=6379 store.redis.sentinel.masterName= store.redis.sentinel.sentinelHosts= store.redis.maxConn=10 store.redis.minConn=1 store.redis.maxTotal=100 store.redis.database=0 store.redis.password= 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 server.distributedLockExpireTime=10000 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.undo.compress.enable=true client.undo.compress.type=zip client.undo.compress.threshold=64k log.exceptionRate=100 transport.serialization=seata transport.compressor=none metrics.enabled=false metrics.registryType=compact metrics.exporterList=prometheus metrics.exporterPrometheusPort=9898 tcc.fence.logTableName=tcc_fence_log tcc.fence.cleanPeriod=1h- 2、nacos-config.sh,conf目錄之下。
用于將配置信息config.txt的值寫入到nacos中
#!/bin/sh # 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 docase $opt inh)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 doneif [ -z ${host} ]; thenhost=localhost fi if [ -z ${port} ]; thenport=8848 fi if [ -z ${group} ]; thengroup="SEATA_GROUP" fi if [ -z ${tenant} ]; thentenant="" fi if [ -z ${username} ]; thenusername="" fi if [ -z ${password} ]; thenpassword="" finacosAddr=$host:$port contentType="content-type:application/json;charset=UTF-8"echo "set nacosAddr=$nacosAddr" echo "set group=$group"urlencode() {length="${#1}"i=0while [ $length -gt $i ]; dochar="${1:$i:1}"case $char in[a-zA-Z0-9.~_-]) printf $char ;;*) printf '%%%02X' "'$char" ;;esaci=`expr $i + 1`done }failCount=0 tempLog=$(mktemp -u) function addConfig() {dataId=`urlencode $1`content=`urlencode $2`curl -X POST -H "${contentType}" "http://$nacosAddr/nacos/v1/cs/configs?dataId=$dataId&group=$group&content=$content&tenant=$tenant&username=$username&password=$password" >"${tempLog}" 2>/dev/nullif [ -z $(cat "${tempLog}") ]; thenecho " Please check the cluster status. "exit 1fiif [ "$(cat "${tempLog}")" == "true" ]; thenecho "Set $1=$2 successfully "elseecho "Set $1=$2 failure "failCount=`expr $failCount + 1`fi }count=0 for line in $(cat $(dirname "$PWD")/config.txt | sed s/[[:space:]]//g); docount=`expr $count + 1`key=${line%%=*}value=${line#*=}addConfig "${key}" "${value}" doneecho "=========================================================================" echo " Complete initialization parameters, total-count:$count , failure-count:$failCount " echo "========================================================================="if [ ${failCount} -eq 0 ]; thenecho " Init nacos config finished, please start seata-server. " elseecho " init nacos config fail. " fi2、載入seata配置到 nacos
運(yùn)行命令
sh nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -t 5d304c31-67d5-479a-a064-6ad7d0c8
-h nacos的ip -g nacos的Group
-t nacos命名空間
3、進(jìn)入nacos
檢查是否寫入成功并修改以下參數(shù)
store.mode的值為db
設(shè)置為自己的數(shù)據(jù)源參數(shù),數(shù)據(jù)庫(kù)名稱默認(rèn)為seata,作為seata臨時(shí)存放分支和全局信息
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?useUnicode=true&rewriteBatchedStatements=true
store.db.user=root
store.db.password=root
4、設(shè)置完成后,修改seata-server配置信息
進(jìn)入seata的conf文件夾,修改registry.conf。
5、導(dǎo)入seata所需的數(shù)據(jù)庫(kù)。
并在每個(gè)服務(wù)的數(shù)據(jù)庫(kù)中導(dǎo)入undo_log表(見文末)。
-- -------------------------------- 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 = InnoDBDEFAULT 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 = InnoDBDEFAULT CHARSET = utf8;-- 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`) ) ENGINE = InnoDBDEFAULT CHARSET = utf8;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);二、seate-client端
1、添加以下依賴
<!--nacos--> <dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <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></dependency>2、修改配置文件application.yml
此處tx-service-group 配置需和config.txt中的vgroupMapping對(duì)應(yīng)(seata1.0之前為vgroup_mapping),見一.2.1.1。
spring:cloud:alibaba:seata:tx-service-group: my_seata_groupseata:config:type: nacosnacos:server-addr: 127.0.0.1:8848group : "SEATA_GROUP"namespace: "cf6ff459-0688-4e0c-97b4-56c8403e107b"username: "nacos"password: "nacos"registry:type: nacosnacos:server-addr: 127.0.0.1:8848group: "SEATA_GROUP"namespace: "cf6ff459-0688-4e0c-97b4-56c8403e107b"username: "nacos"password: "nacos"3、@GlobalTransactional
最后,我們只需要使用一個(gè) @GlobalTransactional 注解在業(yè)務(wù)方法上:
@GlobalTransactionalpublic void purchase(String userId, String commodityCode, int orderCount) {......}undo_log表:
CREATE TABLE undo_log (
id bigint(20) NOT NULL AUTO_INCREMENT,
branch_id bigint(20) NOT NULL,
xid varchar(100) NOT NULL,
context varchar(128) NOT NULL,
rollback_info longblob NOT NULL,
log_status int(11) 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;
總結(jié)
以上是生活随笔為你收集整理的springcloud alibaba + seata 1.3.0 集成文档的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: vue文件目录解析
- 下一篇: Vue 面试题 (全)