自动写作网站,免费定制开发软件,免费做外贸的网站,网站做管理员消息推送目录一、前言二、Nacos集成1、引入Nacos依赖2、设置Nacos配置3、加载Nacos配置中心配置项4、Nacos集成验证5、Nacos配置中心配置项动态生效Nacos安装详见#xff1a;Spring Cloud 系列之 Nacos 配置中心 一、前言
上一篇已经讲解了怎样安装安装、启动、配置 Nacos#xff0c…
目录一、前言二、Nacos集成1、引入Nacos依赖2、设置Nacos配置3、加载Nacos配置中心配置项4、Nacos集成验证5、Nacos配置中心配置项动态生效Nacos安装详见Spring Cloud 系列之 Nacos 配置中心 一、前言
上一篇已经讲解了怎样安装安装、启动、配置 Nacos这篇我们讲解如何在项目中使用 Nacos 。
还不了解 Nacos 的详见Spring Cloud 系列之 Nacos 配置中心
在集成 Nacos 之前首先我们要先创建一个 Spring Boot 项目IDEA 创建 SpringBoot 项目 二、Nacos集成
1、引入Nacos依赖
dependencies!-- nacos --dependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-starter-alibaba-nacos-config/artifactIdversion2.2.1.RELEASE/version/dependencydependencygroupIdcom.alibaba.cloud/groupIdartifactIdspring-cloud-starter-alibaba-nacos-discovery/artifactIdversion2.2.1.RELEASE/version/dependency
dependencies注Spring Boot版本要低于2.4否则启动应用会报错。 2、设置Nacos配置
项目中默认配置文件是 application.properties Nacos 配置加在此配置文件中的话应用启动会报连接 Nacos 失败我们需要创建 bootstrap.properties 或 bootstrap.yml 配置文件添加任意一个即可下面我们以 bootstrap.properties 为例
spring.application.nameapm-mobile-android
spring.cloud.nacos.usernamenacos
spring.cloud.nacos.passwordnacos
spring.cloud.nacos.server-addr10.0.7.115:18117spring.cloud.nacos.discovery.namespacePROD
spring.cloud.nacos.config.namespacePROD
spring.cloud.nacos.config.timeout3000
spring.cloud.nacos.config.refresh-enabledtruespring.cloud.nacos.config.groupapm
spring.cloud.nacos.config.prefix${spring.application.name}
spring.cloud.nacos.config.file-extensionpropertiesspring.cloud.nacos.config.shared-configs[0].groupapm
spring.cloud.nacos.config.shared-configs[0].data-idapm-mobile-android.properties
spring.cloud.nacos.config.shared-configs[0].refreshtruespring.liquibase.enabledfalse3、加载Nacos配置中心配置项
在初始化类中添加 EnableDiscoveryClient 注解即可
package com.example.springbootdemo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;EnableDiscoveryClient
SpringBootApplication
public class SpringbootdemoApplication {public static void main(String[] args) {SpringApplication.run(SpringbootdemoApplication.class, args);new BootstrapManager();}}4、Nacos集成验证
Nacos配置如下 启动应用然后访问http://localhost:8085/hello
出现如下界面说明加载Nacos配置成功。 5、Nacos配置中心配置项动态生效
需要在配置对象中添加 RefreshScope 注解然后重启应用。
package com.example.springbootdemo.config;import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;Data
Component
Configuration
RefreshScope
public class GlobalConfig {Value(${data.domain:http://10.0.0.1:18080})private String dataDomain;Value(${log.level:DEBUG})private String logLevel;
}重启后访问http://localhost:8085/hello 将 Nacos 配置中的 log.level 修改为 DEBUG 然后重新访问http://localhost:8085/hello出现如下界面说明 Nacos 配置动态生成成功。