分布式事务(七):Seata-Server的搭建

1、Seata-Server下载

  官方文档地址:https://seata.io/zh-cn/docs/ops/deploy-guide-beginner.html

  下载地址:https://github.com/seata/seata/releases,这里下载的是1.5.1版本,seata-server-1.5.1.tar.gz。

 0

  解压文件目录如下

 0

2、注册中心配置

  Seata支持的注册中心有file、nacos、eureka、redis、zk、consul、etcd3,这里以Nacos为例,参考conf文件夹下的application.example.yml,修改conf/application.yml配置中注册中心,调整详情如下:

 0

3、配置中心配置

  Seata支持的注册中心有file、nacos、eureka、redis、zk、consul、etcd3,这里以Nacos为例,修改conf/application.yml配置中心,详情如下:

 0

3.1、Seata-Server 1.4.2以前版本的config设置

3.1.1、配置模板config.txt获取

  Seata的一些配置上传到Nacos中,使用官方提供了config.txt模板,修改其中参数,上传到Nacos中,配置模板下载地址:https://github.com/seata/seata/tree/develop/script/config-center

3.1.2、调整config.txt详情

  注意需要注释value为空的配置项,因为value为空的配置项无法通过脚本上传到Nacos的配置中心。

#For details about configuration items, see https://seata.io/zh-cn/docs/user/configurations.html
#Transport configuration, for client and server
transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableTmClientBatchSendRequest=false
transport.enableRmClientBatchSendRequest=true
transport.enableTcServerBatchSendResponse=false
transport.rpcRmRequestTimeout=30000
transport.rpcTmRequestTimeout=30000
transport.rpcTcRequestTimeout=30000
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
transport.serialization=seata
transport.compressor=none

#Transaction routing rules configuration, only for the client
# ===================== 调整事务分组  ======================== 
# === service.vgroupMapping.可以自定义=default,参数值必须与application.yml中的注册中心的cluster的值保持一致,默认都为default ===
service.vgroupMapping.trxgroup=default
#If you use a registry, you can ignore it
# === service.分组值.grouplist 集群搭建时使用,seata-server搭建的IP:PORT ===
service.default.grouplist=192.168.33.55:8091
service.enableDegrade=false
service.disableGlobalTransaction=false
# ===================== 调整事务分组  ========================

#Transaction rule configuration, only for the client
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=true
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
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
#For TCC transaction mode
tcc.fence.logTableName=tcc_fence_log
tcc.fence.cleanPeriod=1h

#Log rule configuration, for client and server
log.exceptionRate=100

#Transaction storage configuration, only for the server. The file, db, and redis configuration values are optional.
# ===================== 调整存储模式为db ======================== 
store.mode=db
store.lock.mode=file
store.session.mode=file
#Used for password encryption
#store.publicKey=
# ===================== 调整存储模式为db ======================== 

#If `store.mode,store.lock.mode,store.session.mode` are not equal to `file`, you can remove the configuration block.
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

#These configurations are required if the `store mode` is `db`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `db`, you can remove the configuration block.
# ===================== 调整JDBC连接配置 ========================
store.db.datasource=druid
store.db.dbType=mysql
store.db.driverClassName=com.mysql.cj.jdbc.Driver
store.db.url=jdbc:mysql://192.168.33.55: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
# ===================== 调整JDBC连接配置 ========================

#These configurations are required if the `store mode` is `redis`. If `store.mode,store.lock.mode,store.session.mode` are not equal to `redis`, you can remove the configuration block.
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

#Transaction rule configuration, only for the server
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
server.xaerNotaRetryTimeout=60000
server.session.branchAsyncQueueSize=5000
server.session.enableBranchAsyncRemove=false
server.enableParallelRequestHandle=false

#Metrics configuration, only for the server
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898

3.1.3、将配置信息添加到seata-server的conf配置文件夹下

0

3.1.4、添加上传脚本

  在地址:https://github.com/seata/seata/tree/develop/script/config-center/nacos中获取需要上传的配置信息脚本nacos-config.sh。

0

  nacos-config.sh脚本详情如下:

#!/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
do
  case $opt in
  h)
    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
done

if [ -z ${host} ]; then
    host=localhost
fi
if [ -z ${port} ]; then
    port=8848
fi
if [ -z ${group} ]; then
    group="SEATA_GROUP"
fi
if [ -z ${tenant} ]; then
    tenant=""
fi
if [ -z ${username} ]; then
    username=""
fi
if [ -z ${password} ]; then
    password=""
fi

nacosAddr=$host:$port
contentType="content-type:application/json;charset=UTF-8"

echo "set nacosAddr=$nacosAddr"
echo "set group=$group"

urlencode() {
  length="${#1}"
  i=0
  while [ $length -gt $i ]; do
    char="${1:$i:1}"
    case $char in
    [a-zA-Z0-9.~_-]) printf $char ;;
    *) printf '%%%02X' "'$char" ;;
    esac
    i=`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/null
  if [ -z $(cat "${tempLog}") ]; then
    echo " Please check the cluster status. "
    exit 1
  fi
  if [ "$(cat "${tempLog}")" == "true" ]; then
    echo "Set $1=$2 successfully "
  else
    echo "Set $1=$2 failure "
    failCount=`expr $failCount + 1`
  fi
}

count=0
COMMENT_START="#"
# 修改config.txt配置文件位置
# for line in $(cat $(dirname "$PWD")/config.txt | sed s/[[:space:]]//g); do
  for line in $(cat ../conf/config.txt | sed s/[[:space:]]//g); do
    if [[ "$line" =~ ^"${COMMENT_START}".*  ]]; then
      continue
    fi
    count=`expr $count + 1`
      key=${line%%=*}
    value=${line#*=}
      addConfig "${key}" "${value}"
done

echo "========================================================================="
echo " Complete initialization parameters,  total-count:$count ,  failure-count:$failCount "
echo "========================================================================="

if [ ${failCount} -eq 0 ]; then
    echo " Init nacos config finished, please start seata-server. "
else
    echo " init nacos config fail. "
fi

  注意:需要调整config.txt配置文件的位置。

3.1.5、Seata配置项上传至Nacos配置中心

5.1、上传脚本参数命令说明

  根据nacos-config.sh脚本中内容,可以得到如下参数:

sh nacos-config.sh -h ip地址 -p 端口号 -g 配置分组 -t 命名空间 -u 用户 -w 密码

参数说明:

  -h:host,nacos的ip地址

  -p:port,nacos的端口号,默认8848

  -g:配置分组,seata默认为SEATA_GROUP

  -t:租户信息,对应Nacos的命名空间ID,默认为空

  -u:nacos用户名

  -w:nacos的密码

5.2、换行符问题

  执行脚本将配置信息上传至Nacos:

sh nacos-config.sh -h 192.168.33.55 -p 8848 -g SEATA_GROUP  -u nacos -w nacos

  出现如下问题:

nacos-config.sh: line 15: $'\r': command not found
nacos-config.sh: line 18: syntax error near unexpected token `$'in\r''
'acos-config.sh: line 18: `  case $opt in
0

问题原因:

  nacos-config.sh脚本文件是在Windows中创建的,内容复制也是在Windows中完成的,通过命令上传至Linux。该问题是因为Linux和Windows的换行符问题导致的。

解决方案:

  执行如下命令安装dos2unix

yum install dos2unix

   转换Windows中的换行符:

dos2unix nacos-config.sh

5.3、部分配置项上传失败问题

  再次执行将配置信息上传至Nacos:

 0

问题原因:

  在config.txt配置中,存在value为空的配置信息,注释这些为空的配置信息,即可解决此问题。

 0

5.4、上传的配置项验证

  Nacos的配置中心详情如下:

 0

3.2、Seata-Server 1.4.2以后版本的config设置

  Seata从1.4.2版本开始,支持从一个Nacos dataId中获取所有配置信息,添加Nacos配置文件,相关属性需要与application.yml中的信息向对象,详情如下:

 0

  新建Nacos配置文件,Data Id为 seataServer.properties,Group为 SEATA_GROUP,properties配置内容为调整后的config.txt,配置详情同Seata1.4.2以前版本的config配置详情:

  0
 0

3.3、Seata-Server 1.4.2前后版本配置中心的不同

  在Seata 1.4.2以前的版本,因为没有dataId配置项,所以config.txt中每一个配置项的key作为dataId,即一个配置项对应一个配置文件;在Seata 1.4.2以后的版本,出现了dataId配置项,可以配置一个dataId管理Seata-Server所有的配置项。

4、Seata存储模式调整

  官方文档地址:https://seata.io/zh-cn/docs/ops/deploy-guide-beginner.html

4.1、存储模式

Server端存储模式(store.mode)支持三种:

  1、file:单机模式,全局事务会话信息内存中读写并持久化本地文件root.data,性能较高(默认)

  2、DB:高可用模式,全局事务会话信息通过DB共享,相对性能差一些

  3、redis:Seata-Server1.3及以上版本支持,性能较高,存在事务信息丢失风险,需要配合实际场景使用。

4.2、配置调整

  修改conf/application.yml配置,调整内容如下:

 0

  使用的mysql版本为8.0以上使用驱动包为com.mysql.cj.jdbc.Driver;8.0以下版本为驱动包为com.mysql.jdbc.Driver。

  application.example.yml示例配置中,有global_table、branch_table、lock_table、distributed_lock这四张表,建表语句地址:https://github.com/seata/seata/blob/develop/script/server/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_status_gmt_modified` (`status` , `gmt_modified`),
    KEY `idx_transaction_id` (`transaction_id`)
) ENGINE = InnoDB
  DEFAULT 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 = InnoDB
  DEFAULT 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 = InnoDB
  DEFAULT 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 = InnoDB
  DEFAULT 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);

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 = InnoDB
  DEFAULT 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);

  执行结果如下:

 0    0               
0     0
 0
 0   0

5、启动Seata

  进入到bin目录,执行启动命令:

sh seata-server.sh

  出现如下日志提示表示服务seata-server启动成功。

 

  访问seata-server的控制台,账密:seata/seata,界面详情如下:

 0
 0

  注册中心服务列表展示如下:

0

  至此,seata-server启动成功。

 

posted @ 2024-02-08 09:50  无虑的小猪  阅读(389)  评论(0编辑  收藏  举报