nacos配置发布和服务订阅

2024-08-26 07:36

本文主要是介绍nacos配置发布和服务订阅,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

nacos安装这里就不说了,官网看即可,以下为单机nacos

(一)nacos客户端

(1) 配置管理配置列表

点击编辑页面如下:
在这里插入图片描述
点击详情页面如下:
在这里插入图片描述

(2) 服务管理服务列表

点击详情页面如下:
在这里插入图片描述

(3) 权限控制权限管理

一定要在权限控制权限管理中给角色和资源赋予读写的权限
在这里插入图片描述

(4) 集群管理节点列表

在这里插入图片描述

如何在/nacos/distribution/bin 控制台(小黑窗,本电脑位mac)起关服务
sh startup.sh -m standalone --单机启动服务
sh shutdown.sh 关闭服务

(二)配置管理和服务管理代码

(1) springboot项目中配置

在springboot项目中建立一个bootstrap.properties

bootstrap.properties 具体配置(nacos配置管理)

# nacos 配置管理 start ===========================
# 默认通过spring.application.name=richfit配置   ${prefix}-${spring.profiles.active}.${file-extension}
#spring.cloud.nacos.config.prefix=richfit
spring.application.name=richfit
#spring.profiles.active=dev
##  使用的 nacos 配置集的 dataId 的文件拓展名,默认为 properties   目前只支持 properties 和 yaml 类型。
spring.cloud.nacos.config.file-extension=properties
##  配置中心
spring.cloud.nacos.config.server-addr=localhost:8848
##  命名空间id  注意:这一定是命名空间id不能是名称!!!!!!
spring.cloud.nacos.config.namespace=53f15a7b-e170-44a2-bb19-c0eb8b3d74f8
##  使用的 nacos 配置分组,默认为 DEFAULT_GROUP
spring.cloud.nacos.config.group=xqy## nacos心跳机制会一直发请求有时候网络不好会报错,把长轮询时间加长会减少此类事故,
## 获取配置的超时时间
#spring.cloud.nacos.config.timeout=5000
#spring.cloud.nacos.config.config-long-poll-timeout=10000
#spring.cloud.nacos.config.config-retry-time=2000
#spring.cloud.nacos.config.max-retry=3## 是否开启监听和自动刷新
spring.cloud.nacos.config.refresh.enabled = true
## nacos心跳机制会一直发请求有时候网络不好会报错,把长轮询时间加长会减少此类事故,## 开启鉴权
## 自己随便定义的  VGhpc0lzTXlDdXN0b21TZWNyZXRLZXkwMTIzNDU2Nzg=
#spring.cloud.nacos.config.access-key=VGhpc0lzTXlDdXN0b21TZWNyZXRLZXkwMTIzNDU2Nzg=
#spring.cloud.nacos.config.secret-key=VGhpc0lzTXlDdXN0b21TZWNyZXRLZXkwMTIzNDU2Nzg=## 共享配置,没有则不加
#spring.cloud.nacos.config.shared-configs=
## 账号
spring.cloud.nacos.config.username=nacos
## 密码
spring.cloud.nacos.config.password=LJ# nacos 配置管理 end ==================================
# nacos end

application.properties 具体配置(nacos服务管理)

# nacos 服务管理 start ================================
#  服务注册
spring.cloud.nacos.discovery.server-addr=localhost:8848
##  命名空间id  注意:这一定是命名空间id不能是名称
spring.cloud.nacos.discovery.namespace=53f15a7b-e170-44a2-bb19-c0eb8b3d74f8
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=LJ
spring.cloud.nacos.discovery.group=xqy
# nacos 服务管理 end ===================================

注意:
1:springboot加载顺序是先bootstrap.properties后application.properties。

2:spring.cloud.nacos.discovery.namespace值必须是命名空间id不能是名称。

RichfitApplication中具体代码:

@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848",namespace = "53f15a7b-e170-44a2-bb19-c0eb8b3d74f8",username = "nacos",password = "LJ"))
@NacosPropertySource(dataId = "richfit.properties",groupId = "xqy",autoRefreshed = true)

具体实例代码如下:

/*** * @return* @throws NacosException* @throws InterruptedException*/@GetMapping("getNacosValue")public String getValue() throws NacosException, InterruptedException {String dataId = "richfit.properties";String group = "xqy";Properties properties = new Properties();properties.put(PropertyKeyConst.SERVER_ADDR, "localhost");//这一定是命名空间id不能是名称properties.put(PropertyKeyConst.NAMESPACE, "53f15a7b-e170-44a2-bb19-c0eb8b3d74f8");properties.put(PropertyKeyConst.USERNAME, "nacos");properties.put(PropertyKeyConst.PASSWORD, "LJ");ConfigService configService = NacosFactory.createConfigService(properties);System.out.println("是否已经连接服务:"+configService.getServerStatus());//是否已经连接服务:UP 代表已连接if ("UP".equalsIgnoreCase(configService.getServerStatus())) {System.out.println("Nacos服务状态正常,服务可用。");// 进行其他业务逻辑处理} else {System.out.println("Nacos服务状态异常,服务不可用。");// 进行错误处理或重试逻辑}String content = configService.getConfig(dataId, group, 5000);System.out.println(content);//下面为监听器,只要客户端中配置改了,下面的addListener就会触发configService.addListener(dataId, group, new Listener() {@Overridepublic void receiveConfigInfo(String configInfo) {System.out.println("receive:" + configInfo);}@Overridepublic Executor getExecutor() {return null;}});//content 是 配置的内容,配置后在发布
//        boolean isPublishOk = configService.publishConfig(dataId, group, "脸脸真可爱,悦悦很可爱,妞妞太可爱");
//        System.out.println(isPublishOk);
//
//        Thread.sleep(3000);
//        //配置完后在获取
//        content = configService.getConfig(dataId, group, 5000);
//        System.out.println(content);return content;}

注意:1:configService.publishConfig为发布修改后的配置。
2: configService.addListener 为监听器,项目启动成功了,只要改nacos 配置管理的配置内容并发布了,那么就会自动触发代码addListener里面的方法。而且会自动在nacos 服务管理里面订阅。下面讲一个改端口的例子。
3:configService.getServerStatus() 检查是否已成功连接nacos服务,返回值UP则为连接成功。

(2)pom文件配置

 <!-- nacos start --><!--nacos配置中心做依赖管理--><dependency><groupId>com.alibaba.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-bootstrap</artifactId><version>3.0.3</version></dependency><!-- nacos服务的注册发现 --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId><version>2.2.3.RELEASE</version></dependency><!-- nacos-client --><dependency><groupId>com.alibaba.nacos</groupId><artifactId>nacos-client</artifactId><version>2.4.1</version></dependency><dependency><groupId>com.alibaba.boot</groupId><artifactId>nacos-config-spring-boot-starter</artifactId><version>0.2.8</version></dependency><!-- nacos end -->

(3)nacos application.properties文件配置

首先 nacos安装包中application.properties位置:

nacos/distribution/target/nacos-server-2.4.1/nacos/conf

nacos application.properties具体配置:

#
# Copyright 1999-2021 Alibaba Group Holding Ltd.
#
# 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.
##*************** Spring Boot Related Configurations ***************#
### Default web context path:
server.servlet.contextPath=/nacos
### Include message field
server.error.include-message=ALWAYS
### Default web server port:
server.port=8848#*************** Network Related Configurations ***************#
### If prefer hostname over ip for Nacos server addresses in cluster.conf:
# nacos.inetutils.prefer-hostname-over-ip=false### Specify local server's IP:
# nacos.inetutils.ip-address=#*************** Config Module Related Configurations ***************#
### If use MySQL as datasource:
### Deprecated configuration property, it is recommended to use `spring.sql.init.platform` replaced.
# spring.datasource.platform=mysql
# spring.sql.init.platform=mysql### Count of DB:
# db.num=1### Connect URL of DB:
db.url.0=jdbc:mysql://localhost:3306/mysql?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=root
db.password.0=hlr2261226HLR### Connection pool configuration: hikariCP
db.pool.config.connectionTimeout=30000
db.pool.config.validationTimeout=10000
db.pool.config.maximumPoolSize=20
db.pool.config.minimumIdle=2### the maximum retry times for push
nacos.config.push.maxRetryTime=50#*************** Naming Module Related Configurations ***************#### If enable data warmup. If set to false, the server would accept request without local data preparation:
# nacos.naming.data.warmup=true### If enable the instance auto expiration, kind like of health check of instance:
# nacos.naming.expireInstance=true### Add in 2.0.0
### The interval to clean empty service, unit: milliseconds.
# nacos.naming.clean.empty-service.interval=60000### The expired time to clean empty service, unit: milliseconds.
# nacos.naming.clean.empty-service.expired-time=60000### The interval to clean expired metadata, unit: milliseconds.
# nacos.naming.clean.expired-metadata.interval=5000### The expired time to clean metadata, unit: milliseconds.
# nacos.naming.clean.expired-metadata.expired-time=60000### The delay time before push task to execute from service changed, unit: milliseconds.
# nacos.naming.push.pushTaskDelay=500### The timeout for push task execute, unit: milliseconds.
# nacos.naming.push.pushTaskTimeout=5000### The delay time for retrying failed push task, unit: milliseconds.
# nacos.naming.push.pushTaskRetryDelay=1000### Since 2.0.3
### The expired time for inactive client, unit: milliseconds.
# nacos.naming.client.expired.time=180000#*************** CMDB Module Related Configurations ***************#
### The interval to dump external CMDB in seconds:
# nacos.cmdb.dumpTaskInterval=3600### The interval of polling data change event in seconds:
# nacos.cmdb.eventTaskInterval=10### The interval of loading labels in seconds:
# nacos.cmdb.labelTaskInterval=300### If turn on data loading task:
# nacos.cmdb.loadDataAtStart=false#***********Metrics for tomcat **************************#
server.tomcat.mbeanregistry.enabled=true#***********Expose prometheus and health **************************#
#management.endpoints.web.exposure.include=prometheus,health### Metrics for elastic search
management.metrics.export.elastic.enabled=false
#management.metrics.export.elastic.host=http://localhost:9200### Metrics for influx
management.metrics.export.influx.enabled=false
#management.metrics.export.influx.db=springboot
#management.metrics.export.influx.uri=http://localhost:8086
#management.metrics.export.influx.auto-create-db=true
#management.metrics.export.influx.consistency=one
#management.metrics.export.influx.compressed=true#*************** Access Log Related Configurations ***************#
### If turn on the access log:
server.tomcat.accesslog.enabled=true### file name pattern, one file per hour
server.tomcat.accesslog.rotate=true
server.tomcat.accesslog.file-date-format=.yyyy-MM-dd-HH
### The access log pattern:
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i### The directory of access log:
server.tomcat.basedir=file:.#*************** Access Control Related Configurations ***************#
### If enable spring security, this option is deprecated in 1.2.0:
#spring.security.enabled=false### The ignore urls of auth
nacos.security.ignore.urls=/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-ui/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**### The auth system to use, currently only 'nacos' and 'ldap' is supported:
nacos.core.auth.system.type=nacos### If turn on auth system:
nacos.core.auth.enabled=true### Turn on/off caching of auth information. By turning on this switch, the update of auth information would have a 15 seconds delay.
nacos.core.auth.caching.enabled=true### Since 1.4.1, Turn on/off white auth for user-agent: nacos-server, only for upgrade from old version.
nacos.core.auth.enable.userAgentAuthWhite=false### Since 1.4.1, worked when nacos.core.auth.enabled=true and nacos.core.auth.enable.userAgentAuthWhite=false.
### The two properties is the white list for auth and used by identity the request from other server.
nacos.core.auth.server.identity.key=nacos
nacos.core.auth.server.identity.value=LJnacos.config.bootstrap.enable=true### worked when nacos.core.auth.system.type=nacos
### The token expiration in seconds:
nacos.core.auth.plugin.nacos.token.cache.enable=true
nacos.core.auth.plugin.nacos.token.expire.seconds=180000000
### The default token (Base64 String): 自己定义的
nacos.core.auth.plugin.nacos.token.secret.key=VGhpc0lzTXlDdXN0b21TZWNyZXRLZXkwMTIzNDU2Nzg=### worked when nacos.core.auth.system.type=ldap,{0} is Placeholder,replace login username
#nacos.core.auth.ldap.url=ldap://localhost:389
#nacos.core.auth.ldap.basedc=dc=example,dc=org
#nacos.core.auth.ldap.userDn=cn=admin,${nacos.core.auth.ldap.basedc}
#nacos.core.auth.ldap.password=admin
#nacos.core.auth.ldap.userdn=cn={0},dc=example,dc=org
#nacos.core.auth.ldap.filter.prefix=uid
#nacos.core.auth.ldap.case.sensitive=true
#nacos.core.auth.ldap.ignore.partial.result.exception=false#*************** Control Plugin Related Configurations ***************#
# plugin type
#nacos.plugin.control.manager.type=nacos# local control rule storage dir, default ${nacos.home}/data/connection and ${nacos.home}/data/tps
#nacos.plugin.control.rule.local.basedir=${nacos.home}# external control rule storage type, if exist
#nacos.plugin.control.rule.external.storage=#*************** Config Change Plugin Related Configurations ***************#
# webhook
#nacos.core.config.plugin.webhook.enabled=false
# It is recommended to use EB https://help.aliyun.com/document_detail/413974.html
#nacos.core.config.plugin.webhook.url=http://localhost:8080/webhook/send?token=***
# The content push max capacity ,byte
#nacos.core.config.plugin.webhook.contentMaxCapacity=102400# whitelist
#nacos.core.config.plugin.whitelist.enabled=false
# The import file suffixs
#nacos.core.config.plugin.whitelist.suffixs=xml,text,properties,yaml,html
# fileformatcheck,which validate the import file of type and content
#nacos.core.config.plugin.fileformatcheck.enabled=false#*************** Istio Related Configurations ***************#
### If turn on the MCP server:
nacos.istio.mcp.server.enabled=false#*************** Core Related Configurations ***************#### set the WorkerID manually
# nacos.core.snowflake.worker-id=### Member-MetaData
# nacos.core.member.meta.site=
# nacos.core.member.meta.adweight=
# nacos.core.member.meta.weight=### MemberLookup
### Addressing pattern category, If set, the priority is highest
# nacos.core.member.lookup.type=[file,address-server]
## Set the cluster list with a configuration file or command-line argument
# nacos.member.list=192.168.16.101:8847?raft_port=8807,192.168.16.101?raft_port=8808,192.168.16.101:8849?raft_port=8809
## for AddressServerMemberLookup
# Maximum number of retries to query the address server upon initialization
# nacos.core.address-server.retry=5
## Server domain name address of [address-server] mode
# address.server.domain=jmenv.tbsite.net
## Server port of [address-server] mode
# address.server.port=8080
## Request address of [address-server] mode
# address.server.url=/nacos/serverlist#*************** JRaft Related Configurations ***************#### Sets the Raft cluster election timeout, default value is 5 second
# nacos.core.protocol.raft.data.election_timeout_ms=5000
### Sets the amount of time the Raft snapshot will execute periodically, default is 30 minute
# nacos.core.protocol.raft.data.snapshot_interval_secs=30
### raft internal worker threads
# nacos.core.protocol.raft.data.core_thread_num=8
### Number of threads required for raft business request processing
# nacos.core.protocol.raft.data.cli_service_thread_num=4
### raft linear read strategy. Safe linear reads are used by default, that is, the Leader tenure is confirmed by heartbeat
# nacos.core.protocol.raft.data.read_index_type=ReadOnlySafe
### rpc request timeout, default 5 seconds
# nacos.core.protocol.raft.data.rpc_request_timeout_ms=5000#*************** Distro Related Configurations ***************#### Distro data sync delay time, when sync task delayed, task will be merged for same data key. Default 1 second.
# nacos.core.protocol.distro.data.sync.delayMs=1000### Distro data sync timeout for one sync data, default 3 seconds.
# nacos.core.protocol.distro.data.sync.timeoutMs=3000### Distro data sync retry delay time when sync data failed or timeout, same behavior with delayMs, default 3 seconds.
# nacos.core.protocol.distro.data.sync.retryDelayMs=3000### Distro data verify interval time, verify synced data whether expired for a interval. Default 5 seconds.
# nacos.core.protocol.distro.data.verify.intervalMs=5000### Distro data verify timeout for one verify, default 3 seconds.
# nacos.core.protocol.distro.data.verify.timeoutMs=3000### Distro data load retry delay when load snapshot data failed, default 30 seconds.
# nacos.core.protocol.distro.data.load.retryDelayMs=30000### enable to support prometheus service discovery
#nacos.prometheus.metrics.enabled=true### Since 2.3
#*************** Grpc Configurations ***************### sdk grpc(between nacos server and client) configuration
## Sets the maximum message size allowed to be received on the server.
#nacos.remote.server.grpc.sdk.max-inbound-message-size=10485760## Sets the time(milliseconds) without read activity before sending a keepalive ping. The typical default is two hours.
#nacos.remote.server.grpc.sdk.keep-alive-time=7200000## Sets a time(milliseconds) waiting for read activity after sending a keepalive ping. Defaults to 20 seconds.
#nacos.remote.server.grpc.sdk.keep-alive-timeout=20000## Sets a time(milliseconds) that specify the most aggressive keep-alive time clients are permitted to configure. The typical default is 5 minutes
#nacos.remote.server.grpc.sdk.permit-keep-alive-time=300000## cluster grpc(inside the nacos server) configuration
#nacos.remote.server.grpc.cluster.max-inbound-message-size=10485760## Sets the time(milliseconds) without read activity before sending a keepalive ping. The typical default is two hours.
#nacos.remote.server.grpc.cluster.keep-alive-time=7200000## Sets a time(milliseconds) waiting for read activity after sending a keepalive ping. Defaults to 20 seconds.
#nacos.remote.server.grpc.cluster.keep-alive-timeout=20000## Sets a time(milliseconds) that specify the most aggressive keep-alive time clients are permitted to configure. The typical default is 5 minutes
#nacos.remote.server.grpc.cluster.permit-keep-alive-time=300000## open nacos default console ui
#nacos.console.ui.enabled=true

nacos.core.auth.plugin.nacos.token.secret.key 这个值设置一个大于32位base64值即可,也就这一处设置,设置成功就不要动了,springboot项目中不用设置!!!

(三)nacos配置管理内容中端口修改发布后,springboot项目启动导致项目最终端口改变

首先nacos配置内容端口改变:
在这里插入图片描述

然后springboot项目启动成功
在这里插入图片描述

发现springboot application.properties原本配置server.port = 8887 ,结果项目跑成功后控制台打印的是8886(此端口是nacos中配置的端口),而且从打印其他信息来看确实nacos注册成功了。

最后用8886请求接口返回nacos中配置的内容
在这里插入图片描述

这篇关于nacos配置发布和服务订阅的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1107948

相关文章

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

定价129元!支持双频 Wi-Fi 5的华为AX1路由器发布

《定价129元!支持双频Wi-Fi5的华为AX1路由器发布》华为上周推出了其最新的入门级Wi-Fi5路由器——华为路由AX1,建议零售价129元,这款路由器配置如何?详细请看下文介... 华为 Wi-Fi 5 路由 AX1 已正式开售,新品支持双频 1200 兆、配有四个千兆网口、提供可视化智能诊断功能,建

TP-Link PDDNS服将于务6月30日正式停运:用户需转向第三方DDNS服务

《TP-LinkPDDNS服将于务6月30日正式停运:用户需转向第三方DDNS服务》近期,路由器制造巨头普联(TP-Link)在用户群体中引发了一系列重要变动,上个月,公司发出了一则通知,明确要求所... 路由器厂商普联(TP-Link)上个月发布公告要求所有用户必须完成实名认证后才能继续使用普联提供的 D

SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤

《SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤》本文主要介绍了SpringBoot+MyBatis-Flex配置ProxySQL的实现步骤,文中通过示例代码介绍的非常详... 目录 目标 步骤 1:确保 ProxySQL 和 mysql 主从同步已正确配置ProxySQL 的

Spring Boot整合log4j2日志配置的详细教程

《SpringBoot整合log4j2日志配置的详细教程》:本文主要介绍SpringBoot项目中整合Log4j2日志框架的步骤和配置,包括常用日志框架的比较、配置参数介绍、Log4j2配置详解... 目录前言一、常用日志框架二、配置参数介绍1. 日志级别2. 输出形式3. 日志格式3.1 PatternL

配置springboot项目动静分离打包分离lib方式

《配置springboot项目动静分离打包分离lib方式》本文介绍了如何将SpringBoot工程中的静态资源和配置文件分离出来,以减少jar包大小,方便修改配置文件,通过在jar包同级目录创建co... 目录前言1、分离配置文件原理2、pom文件配置3、使用package命令打包4、总结前言默认情况下,

微服务架构之使用RabbitMQ进行异步处理方式

《微服务架构之使用RabbitMQ进行异步处理方式》本文介绍了RabbitMQ的基本概念、异步调用处理逻辑、RabbitMQ的基本使用方法以及在SpringBoot项目中使用RabbitMQ解决高并发... 目录一.什么是RabbitMQ?二.异步调用处理逻辑:三.RabbitMQ的基本使用1.安装2.架构

VScode连接远程Linux服务器环境配置图文教程

《VScode连接远程Linux服务器环境配置图文教程》:本文主要介绍如何安装和配置VSCode,包括安装步骤、环境配置(如汉化包、远程SSH连接)、语言包安装(如C/C++插件)等,文中给出了详... 目录一、安装vscode二、环境配置1.中文汉化包2.安装remote-ssh,用于远程连接2.1安装2

Java中使用Java Mail实现邮件服务功能示例

《Java中使用JavaMail实现邮件服务功能示例》:本文主要介绍Java中使用JavaMail实现邮件服务功能的相关资料,文章还提供了一个发送邮件的示例代码,包括创建参数类、邮件类和执行结... 目录前言一、历史背景二编程、pom依赖三、API说明(一)Session (会话)(二)Message编程客

Redis多种内存淘汰策略及配置技巧分享

《Redis多种内存淘汰策略及配置技巧分享》本文介绍了Redis内存满时的淘汰机制,包括内存淘汰机制的概念,Redis提供的8种淘汰策略(如noeviction、volatile-lru等)及其适用场... 目录前言一、什么是 Redis 的内存淘汰机制?二、Redis 内存淘汰策略1. pythonnoe