springcloud 整合新版本seata、nacos并测试验证

前言: 参考了博客:springcloud和seata和nacos整合详细教程
在此感谢博主的分享

springcloud 整合新版本seata、nacos

  1. 版本:
    nacos: nacos-server-2.0.3.zip nacos官方地址:
    seata: seata-server-1.4.0.zip seata官方地址:
    mysql: 8.0.19

项目gitee地址: https://gitee.com/qinenqi/seata-test

nacos 配置

  1. 下载并解压
    在这里插入图片描述
  2. 新建 一个 nacos 数据库
  3. 进入 nacos\conf 目录下 把nacos-mysql.sql数据插入到 nacos数据库中
    在这里插入图片描述
  4. 进入 nacos\conf 目录下 打开文件 application.properties。修改一下内容:
    在这里插入图片描述
    把对应的注释打开,修改数据库相关信息
spring.datasource.platform=mysql

### Count of DB:
db.num=1

### Connect URL of DB:
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=root
db.password.0=root
  1. 进入 nacos\bin, 修改startup.cmd文件
    在这里插入图片描述
    把 26行改成 set MODE=“standalone”
  2. 启动服务: 双击 startup.cmd
  3. 访问: http://192.168.88.1:8848/nacos/index.html 用户名和密码: nacos nacos
    在这里插入图片描述
  4. 新建命名空间: 新建一个 seata 的命名空间
    在这里插入图片描述
    新建好的如下:
    在这里插入图片描述

seata 安装

  1. 下载并解压
    在这里插入图片描述
  2. 创建数据库 seata,并把 mysql.sql 文件导入到数据库 https://github.com/seata/seata/blob/develop/script/server/db/mysql.sql
    在这里插入图片描述
    在这里插入图片描述
  3. 进入 seata\conf 修改 registry.conf:
    在这里插入图片描述
registry {
  # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
  type = "nacos"
  loadBalance = "RandomLoadBalance"
  loadBalanceVirtualNodes = 10

  nacos {
    application = "seata-server"
    serverAddr = "127.0.0.1:8848"
    group = "SEATA_GROUP"
    namespace = ""
    cluster = "default"
    username = "nacos"
    password = "nacos"
  }

  file {
    name = "file.conf"
  }
}

config {
  # file、nacos 、apollo、zk、consul、etcd3
  type = "nacos"

  nacos {
    serverAddr = "127.0.0.1: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"
  }
}

  1. 进入 seata 新建 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.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.sqlParserType=druid
client.rm.reportSuccessEnable=false
client.rm.sagaBranchRegisterEnable=false
client.tm.commitRetryCount=5
client.tm.rollbackRetryCount=5
client.tm.defaultGlobalTransactionTimeout=60000
client.tm.degradeCheck=false
client.tm.degradeCheckAllowTimes=10
client.tm.degradeCheckPeriod=2000
store.mode=db
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.cj.jdbc.Driver
store.db.url=jdbc:mysql://127.0.0.1:3306/seata?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=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.queryLimit=100
store.db.lockTable=lock_table
store.db.maxWait=5000
store.redis.host=127.0.0.1
store.redis.port=6379
store.redis.maxConn=10
store.redis.minConn=1
store.redis.database=0
store.redis.password=null
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
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


5. 在 conf 目录下, 新建 nacos-config.sh 文件, nacos-config.sh 地址: 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
for line in $(cat $(dirname "$PWD")/config.txt | sed s/[[:space:]]//g); do
    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

新建完成后如下:
在这里插入图片描述
在这里插入图片描述

  1. 在conf目录下,打开git bash,输入 sh nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -t
    9c8bc235-49eb-452d-b1d3-aae263f74fa3 -u nacos -w nacos,其中-t是nacos命名空间,可删除(当然建议给seata单独建命名空间,这样以后配置多了,可以很直观的找到),这个命名空间就是我们刚刚新建的seata的id,不能乱输入,不然nacos配置文件没有
 sh nacos-config.sh -h localhost -p 8848 -g SEATA_GROUP -t 	9c8bc235-49eb-452d-b1d3-aae263f74fa3 -u nacos -w nacos

在这里插入图片描述
其中config.txt是配置文件,耳nacos-config.sh的作用是将配置文件的属性注入到nacos中(把一些配置属性推送到nacos中),这样就不需要将registry.conf放到我们的项目里。
7. 看到这些 则说明加载成功了
在这里插入图片描述
在这里插入图片描述

项目整合

项目gitee地址: https://gitee.com/qinenqi/seata-test

  1. 在需要的每个项目中引入依赖:
        <!--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>1.4.0</version>
        </dependency>

小编是seata-server-1.4.0.zip这个版本的,请根据自己的实际情况引入不同seata的版本
2. seata 相关的配置

server:
  port: 2002

spring:
  application:
    name: seata-storage
  cloud:
    alibaba:
    #      seata:
    #        #自定义事务组名称需要与seata-server中的对应
    #        tx-service-group: my_test_tx_group
    nacos:
      discovery:
        server-addr: localhost:8848
        username: nacos
        password: nacos
        group: SEATA_GROUP
  #        namespace: c9829d3b-5e7c-4d41-b0f1-00c4240c9c21 不指定命名空间。默认public
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/seata_storage?useUnicode=true&characterEncoding=utf-8&useSSL=NO&serverTimezone=Asia/Shanghai
    username: root
    password: root

feign:
  hystrix:
    enabled: false

logging:
  level:
    io:
      seata: info

mybatis:
  mapperLocations: classpath:mapper/*.xml

seata:
  tx-service-group: my_test_tx_group #这里要特别注意和nacos中配置的要保持一直
  registry:
    type: nacos
    nacos:
      server-addr: ${spring.cloud.nacos.discovery.server-addr}
      username: ${spring.cloud.nacos.discovery.username}
      password: ${spring.cloud.nacos.discovery.password}
      group: ${spring.cloud.nacos.discovery.group}
      #namespace: c9829d3b-5e7c-4d41-b0f1-00c4240c9c21 默认public
  config:
    type: nacos
    nacos:
      server-addr: ${spring.cloud.nacos.discovery.server-addr}
      username: ${spring.cloud.nacos.discovery.username}
      password: ${spring.cloud.nacos.discovery.password}
      group: ${spring.cloud.nacos.discovery.group}
      namespace: d8601be2-7672-43d7-8014-7a4cbb3909ae  #2.2中配置所在命名空间ID,入未配置 默认public空间
  service:
    vgroup-mapping:
      my_test_tx_group: seata-group		# 这里要特别注意和nacos中配置的要保持一致,与这个配置 service.vgroupMapping.my_test_tx_group=seata-group
 

在这里插入图片描述
3. 每个对应的业务数据库,新建一张 undo_log

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 80019
 Source Host           : localhost:3306
 Source Schema         : seata_order

 Target Server Type    : MySQL
 Target Server Version : 80019
 File Encoding         : 65001

 Date: 14/06/2022 13:43:14
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

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

SET FOREIGN_KEY_CHECKS = 1;

  1. 相关的业务逻辑
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    上面是小编的简单截图,具体的项目代码,请参考: 项目gitee地址: https://gitee.com/qinenqi/seata-test

seata配置异常

  1. 报错信息:
2022-06-14 14:49:49.105 ERROR 8044 --- [           main] i.s.c.r.netty.NettyClientChannelManager  : no available service found in cluster 'xxx', please make sure registry config correct and keep your seata server running
2022-06-14 14:49:49.285  INFO 8044 --- [           main] i.s.s.a.GlobalTransactionScanner         : Bean[com.example.seataorder.service.OrderServiceImpl] with name [orderServiceImpl] would use interceptor [io.seata.spring.annotation.GlobalTransactionalInterceptor]
2022-06-14 14:49:49.333  WARN 8044 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2022-06-14 14:49:49.333  INFO 8044 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2022-06-14 14:49:49.338  WARN 8044 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2022-06-14 14:49:49.338  INFO 8044 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2022-06-14 14:49:49.491  INFO 8044 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2022-06-14 14:49:51.226  INFO 8044 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2022-06-14 14:49:51.232  INFO 8044 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'Nacso-Watch-Task-Scheduler'
2022-06-14 14:49:53.213  INFO 8044 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2022-06-14 14:49:53.258  INFO 8044 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2022-06-14 14:49:53.369  INFO 8044 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 2001 (http) with context path ''
2022-06-14 14:49:53.400  INFO 8044 --- [           main] c.a.c.n.registry.NacosServiceRegistry    : nacos registry, SEATA_GROUP seata-order 192.168.88.1:2001 register finished
2022-06-14 14:49:54.929  INFO 8044 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2022-06-14 14:49:54.947  INFO 8044 --- [           main] c.e.seataorder.SeataOrderApplication     : Started SeataOrderApplication in 14.082 seconds (JVM running for 15.361)
2022-06-14 14:49:55.806  INFO 8044 --- [7)-192.168.88.1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-06-14 14:49:55.806  INFO 8044 --- [7)-192.168.88.1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-06-14 14:49:55.816  INFO 8044 --- [7)-192.168.88.1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 10 ms
2022-06-14 14:50:47.266 ERROR 8044 --- [eoutChecker_1_1] i.s.c.r.netty.NettyClientChannelManager  : no available service found in cluster 'xxx', please make sure registry config correct and keep your seata server running
2022-06-14 14:50:47.298 ERROR 8044 --- [eoutChecker_2_1] i.s.c.r.netty.NettyClientChannelManager  : no available service found in cluster 'xxx', please make sure registry config correct and keep your seata server running
2022-06-14 14:50:57.260 ERROR 8044 --- [eoutChecker_1_1] i.s.c.r.netty.NettyClientChannelManager  : no available service found in cluster 'xxx', please make sure registry config correct and keep your seata server running
2022-06-14 14:50:57.291 ERROR 8044 --- [eoutChecker_2_1] i.s.c.r.netty.NettyClientChannelManager  : no available service found in cluster 'xxx', please make sure registry config correct and keep your seata server running
2022-06-14 14:51:07.259 ERROR 8044 --- [eoutChecker_1_1] i.s.c.r.netty.NettyClientChannelManager  : no available service found in cluster 'xxx', please make sure registry config correct and keep your seata server running
2022-06-14 14:51:07.290 ERROR 8044 --- [eoutChecker_2_1] i.s.c.r.netty.NettyClientChannelManager  : no available service found in cluster 'xxx', please make sure registry config correct and keep your seata server running

在这里插入图片描述
则说明 项目中的 my_test_tx_group: default 的值与nacos中配置的值不一致。

项目中的配置
在这里插入图片描述
nacos中的配置在这里插入图片描述
把nacos中的配置更改为default即可,项目正常启动。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于这个问题,我可以提供一些参考资料。首先,Spring Cloud是一个基于Spring框架的微服务架构开发工具包,提供丰富的开箱即用的组件和框架,可以较为方便地实现微服务的开发、部署和管理。而Nacos是阿里巴巴开源的一个面向服务中心的动态服务发现、配置管理和服务治理平台,可以提供服务注册与发现、配置管理、流量管理、域名解析等功能。Seata是阿里巴巴开源的一个分布式事务解决方案,可以提供数据源代理、事务协调、幂等性设计等功能,用于解决微服务架构下的分布式事务问题。 在Spring Cloud中集成NacosSeata,需要进行如下步骤: 1. 引入相应的依赖,例如在pom.xml文件中添加如下依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> <version>2.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>2.2.3.RELEASE</version> </dependency> <dependency> <groupId>io.seata</groupId> <artifactId>seata-spring-boot-starter</artifactId> <version>1.4.2</version> </dependency> ``` 其中,spring-cloud-starter-alibaba-nacos-config和spring-cloud-starter-alibaba-nacos-discovery是Nacos的客户端依赖,seata-spring-boot-starter是Seata的客户端依赖。 2. 配置Nacos的地址和Seata的事务配置,例如在application.yml文件中添加如下配置: ```yaml spring: cloud: nacos: discovery: server-addr: localhost:8848 config: server-addr: localhost:8848 file-extension: yml seata: tx-service-group: my_test_tx_group application-id: ${spring.application.name} enabled: true mybatis: configuration: # ... seata: enabled: true application-id: ${spring.application.name} tx-service-group: my_test_tx_group config: transport: enabled: true type: TCP server: localhost:8091 heartbeat: true heartbeat.interval.ms: 5000 disableHeartbeatChecking: true client-selector: rnd client-list: 127.0.0.1:8091 shutdown.timeout.ms: 5000 registry: type: Nacos nacos: application: ${spring.application.name} serverAddr: localhost:8848 namespace: public ``` 其中,Nacos的地址和Seata的事务配置可以根据具体情况自行修改。 3. 配置完毕后,就可以使用Nacos作为Spring Cloud的注册中心和配置中心,使用Seata来解决分布式事务问题了。 以上是关于如何在Spring Cloud中集成NacosSeata的简要介绍,希望能够帮助到你。如果你还有其他问题,可以继续向我提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值