Appearance
使用Nocos实现中心化动态配置管理
通过 Nacos Server
和 spring-cloud-starter-alibaba-nacos-config
实现配置的动态变更。
前提条件
您需要先下载 Nacos
并启动 Nacos server
。
启动配置管理
在Nacos Server已启动的前提下,您可以按以下步骤,为 Spring Cloud
应用启动 Nacos
配置管理服务了。
添加 nacos-config
依赖
在项目 pom.xml
文件中添加如下依赖:
xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2021.1</version>
</dependency>
启用 bootstrap
配置文件
从 Spring Boot 2.4 版本开始,默认不加载 bootstarp
的配置信息,需要增加如下依赖来开启 bootstarp
加载:
xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
配置 Nacos
连接信息
在 bootstrap.yml
文件中配置 Nacos server
连接信息,如下:
yml
spring:
application:
name: config-test
# version: 1.0
cloud:
nacos:
config:
server-addr: localhost:8848
username: nacos
password: nacos
refresh-enabled: true
file-extension: yaml
# namespace: 79da9dd8-726e-4cd1-843a-d1c042e2d07f
# group: dev-test-2
# 以下是共享配置引用
shared-configs[0]:
data-id: db-config.yaml
# group: dev-test-2
refresh: true
说明
之所以需要配置 spring.application.name ,是因为它是构成 Nacos 配置管理 dataId字段的一部分。
在 Nacos Spring Cloud
中,dataId
的完整格式如下:
${prefix}-${spring.profiles.active}.${file-extension}
prefix
默认为spring.application.name
的值,也可以通过配置项spring.cloud.nacos.config.prefix
来配置。spring.profiles.active
即为当前环境对应的profile
,详情可以参考Spring Boot
文档。 注意:当spring.profiles.active
为空时,对应的连接符-
也将不存在,dataId
的拼接格式变成${prefix}.${file-extension}
file-exetension
为配置内容的数据格式,可以通过配置项spring.cloud.nacos.config.file-extension
来配置。目前只支持properties
和yaml
类型。
Java属性自动更新
通过 Spring Cloud
原生注解 @RefreshScope
实现配置自动更新:
java
@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {
@Value("${useLocalCache:false}")
private boolean useLocalCache;
@RequestMapping("/get")
public boolean get() {
return useLocalCache;
}
}
验证
首先通过Nacos Server
配置管理下的配置列表,创建一个 dataId
为 config-test.yaml
,Group
为 DEFAULT_GROUP
,内容为 useLocalCache:true
的配置信息
yaml
useLocalCache:true
运行 NacosConfigApplication
,访问 http://localhost:8080/config/get
,返回内容是 true
。
通过Nacos Server
配置管理下的配置列表,修改并发布dataId
为 config-test.yaml
,Group
为 DEFAULT_GROUP
,内容为 useLocalCache:false
再次访问 http://localhost:8080/config/get
,此时返回内容为 false
,说明程序中的 useLocalCache
值已经被动态更新了。
参考资料
Nacos
官方文档:https://nacos.io/zh-cn/docs/quick-start-spring-cloud.html