1、docker拉取并且运行镜像

需要配置好的nacos与seata表的数据库(sql代码很容易找到我就不贴了)
docker run -d --name seata -p 8091:8091 -e SEATA_IP=你想指定的ip -e SEATA_PORT=8091 seataio/seata-server:latest
踩坑1:
如果配置在云服务器,这个seata_ip一定要写,本地可以不写。不然注册到nacos里面的是容器的本地ip,那样的话,就不能ping通,因此客户端就无法访问到seata。
报错 can not register RM,err:can not connect to services-server.

解决can not connect to services-server
docker cp 容器id:seata-server/resources 你想放置的linux本地目录
resources里面的目录大概如下,没标红的不必理会
在这里插入图片描述

2、将其注册进nacos,并且将nacos作为seata的配置中心

配置registry.conf

registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  # 注册进nacos
  type = "nacos"
  loadBalance = "RandomLoadBalance"
  loadBalanceVirtualNodes = 10

  nacos {
    application = "seata-server"
    serverAddr = "nacosip:8848"
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = "nacos"
    password = "nacos"
  }
  eureka {
    serviceUrl = "http://localhost:8761/eureka"
    application = "default"
    weight = "1"
  }
  redis {
    serverAddr = "localhost:6379"
    db = 0
    password = ""
    cluster = "default"
    timeout = 0
  }
  zk {
    cluster = "default"
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  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
  # 设置nacos 作为配置中心
  type = "nacos"
  nacos {
    serverAddr = "nacosip:8848"
    namespace = ""
    group = "SEATA_GROUP"
    username = "nacos"
    password = "nacos"
  }
  consul {
    serverAddr = "127.0.0.1:8500"
  }
  apollo {
    appId = "seata-server"
    apolloMeta = "http://192.168.1.204:8801"
    namespace = "application"
    apolloAccesskeySecret = ""
  }
  zk {
    serverAddr = "127.0.0.1:2181"
    sessionTimeout = 6000
    connectTimeout = 2000
    username = ""
    password = ""
  }
  etcd3 {
    serverAddr = "http://localhost:2379"
  }
  file {
    name = "file.conf"
  }
}

配置好之后docker cp registry文件的本地路径 容器id:seata-server/resources/registry.conf
重启seata
docker restart seata
到这里按道理seata会注册到nacos。并且显示的ip是你的外网ip
在这里插入图片描述

3、配置db数据库连接,并且添加service

## transaction log store, only used in seata-server

## 手动添加service,设置事务组的名称为my_test_tx_group

service {
  vgroupMapping.my_test_tx_group = "default"
  disableGlobalTransaction = false
}
store {
  ## store mode: file、db、redis
  mode = "db"

  ## file store property
  file {
    ## store location dir
    dir = "sessionStore"
    # branch session size , if exceeded first try compress lockkey, still exceeded throws exceptions
    maxBranchSessionSize = 16384
    # globe session size , if exceeded throws exceptions
    maxGlobalSessionSize = 512
    # file buffer size , if exceeded allocate new buffer
    fileWriteBufferCacheSize = 16384
    # when recover batch read size
    sessionReloadReadSize = 100
    # async, sync
    flushDiskMode = async
  }
 ##配置db数据库连接
  ## database store property
  db {
    ## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp)/HikariDataSource(hikari) etc.
    datasource = "druid"
    ## mysql/oracle/postgresql/h2/oceanbase etc.
    dbType = "mysql"
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://数据库ip:端口/seata"
    user = "root"
    password = "密码"
    minConn = 5
    maxConn = 100
    globalTable = "global_table"
    branchTable = "branch_table"
  ## redis store property
  redis {
    host = "127.0.0.1"
    port = "6379"
    password = ""
    database = "0"
    minConn = 1
    maxConn = 10
    queryLimit = 100
  }

同样docker cp 类似于上面的

4、向nacos里面导入seata需要的配置

官网给我们提供了两个文件,一个是.sh文件,一个是config.txt文件
config.txt
.sh和他在一起,位于nacos文件夹里,在linux系统里(在windows可以用git执行下面的命令)
config.txt

transport.type=TCP
transport.server=NIO
transport.heartbeat=true
transport.enableClientBatchSendRequest=false
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_test_tx_group=default
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.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
store.mode=file
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://数据库ip:端口/seata?useUnicode=true
store.db.user=root
store.db.password=密码
store.db.minConn=5
store.db.maxConn=30
store.db.globalTable=global_table
store.db.branchTable=branch_table
store.db.queryLimit=100
store.db.lockTable=lock_table
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
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.log.exceptionRate=100
transport.serialization=seata
transport.compressor=none
metrics.enabled=false
metrics.registryType=compact
metrics.exporterList=prometheus
metrics.exporterPrometheusPort=9898

linux脚本文件

#!/usr/bin/env bash
# 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"

failCount=0
tempLog=$(mktemp -u)
function addConfig() {
  curl -X POST -H "${contentType}" "http://$nacosAddr/nacos/v1/cs/configs?dataId=$1&group=$group&content=$2&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++ ))
  fi
}

count=0
for line in $(cat $(dirname "$PWD")/config.txt | sed s/[[:space:]]//g); do
  (( count++ ))
	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

执行

sh ${SEATAPATH}/script/config-center/nacos/nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -t 5a3c7d6c-f497-4d68-a71a-2e5e3340b3ca -u username -w password

关于参数的说明
参数说明:

-h:主机,默认值为localhost。配置到服务器必填,为nacos的地址

-p:端口,默认值为8848。

-g:配置分组,默认值为“ SEATA_GROUP”。

-t:namespace信息,对应于Nacos的名称空间ID字段,默认值为空。

-u:用户名,权限控制上的nacos 1.2.0+,默认值为。nacos1.2.0以上必填 为nacos

-w:密码,权限控制上的nacos 1.2.0+,默认值为。nacos1.2.0以上必填 为nacos
按道理会出现成功导入的页面信息
在这里插入图片描述

5、springboot 客户端的配置

server:
  port: 2002
spring:
  application:
    name: seata-storage-service
  cloud:
    alibaba:
      seata:
        tx-service-group: my_test_tx_group
    nacos:
      discovery:
        server-addr: nacos的IP:8848 # 注册nacos
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://数据库ip:3307/seata_storage?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
    username: root
    password: aiMONEY157732
feign:
  hystrix:
    enabled: false

mybatis:
  mapperLocations: classpath:mapper/*.xml
logging:
  level:
    io:
      seata: info

5.1 关于事务组的说明

读取配置
通过NacosConfiguration远程读取seata配置参数

获取事务分组
springboot可配置在yml、properties中,服务启动时加载配置,对应的值"my_test_tx_group"即为一个事务分组名,若不配置,默认获取属性spring.application.name的值+"-fescar-service-group"

查找TC集群名
拿到事务分组名"my_test_tx_group"拼接成"service.vgroupMapping.my_test_tx_group"从配置中心查找到TC集群名clusterName为"default"

查找TC服务
根据serverAddr和namespace以及clusterName在注册中心找到真实TC服务列表

注:serverAddr和namespace与Server端一致,clusterName与Server端cluster一致
以上取自官网客户端关于事务分组的说明我的理解是,在nacos读取到的配置信息是在这里插入图片描述
yml读取到的事务组为my_test_tx_group,然后拼接成service.vgroupMapping.my_test_tx_group,他的值在配置中心显示的是default,然后在服务注册的列表找到该集群,然后往该服务的ip+端口号注册在这里插入图片描述

6、粘贴配置好的file.conf和registry.conf到resource

在这里插入图片描述
在这里插入图片描述
file.conf文件这里如果seata版本大于1.1.0,一定写成vgroupMapping.my_test_tx_group 而不是 vgroup_mapping.my_test_tx_group
1.1版本以上的seata组名用大写的M,不然还是会报没有可用的服务错误
错误如下

 i.s.c.r.netty.NettyClientChannelManager  : no available service 'null' found, please make sure registry config correct

分析错误的时候看源码的好处从上面的链接能看出来

7、重启spring boot

在这里插入图片描述
链接seata成功。

排错是痛苦的,但是假如能排完那就是值得的。在排错的时候,看错误日志,走debug,查资料显得尤为重要

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐