Nacos安装详见:Spring Cloud 系列之 Nacos 配置中心
上一篇已经讲解了怎样安装安装、启动、配置 Nacos,这篇我们讲解如何在项目中使用 Nacos 。
还不了解 Nacos 的详见:Spring Cloud 系列之 Nacos 配置中心
在集成 Nacos 之前,首先我们要先创建一个 Spring Boot 项目:IDEA 创建 SpringBoot 项目
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<dependencies> <!-- nacos --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> <version>2.2.1.RELEASE</version> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>2.2.1.RELEASE</version> </dependency> <dependencies> |
注:Spring Boot版本要低于2.4,否则启动应用会报错。

项目中默认配置文件是 application.properties ,Nacos 配置加在此配置文件中的话,应用启动会报连接 Nacos 失败,我们需要创建 bootstrap.properties 或 bootstrap.yml 配置文件(添加任意一个即可),下面我们以 bootstrap.properties 为例:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
spring.application.name=apm-mobile-android spring.cloud.nacos.username=nacos spring.cloud.nacos.password=nacos spring.cloud.nacos.server-addr=10.0.7.115:18117 spring.cloud.nacos.discovery.namespace=PROD spring.cloud.nacos.config.namespace=PROD spring.cloud.nacos.config.timeout=3000 spring.cloud.nacos.config.refresh-enabled=true spring.cloud.nacos.config.group=apm spring.cloud.nacos.config.prefix=${spring.application.name} spring.cloud.nacos.config.file-extension=properties spring.cloud.nacos.config.shared-configs[0].group=apm spring.cloud.nacos.config.shared-configs[0].data-id=apm-mobile-android.properties spring.cloud.nacos.config.shared-configs[0].refresh=true spring.liquibase.enabled=false |

在初始化类中添加 @EnableDiscoveryClient 注解即可:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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(); } } |

Nacos配置如下:

启动应用,然后访问:http://localhost:8085/hello
出现如下界面说明加载Nacos配置成功。

需要在配置对象中添加 @RefreshScope 注解,然后重启应用。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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 配置动态生成成功。

from:https://blog.csdn.net/wangzhongshun/article/details/122369394