本文主要是介绍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配置发布和服务订阅的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!