0%

使用Nacos配置中心

使用Nacos配置中心

Nacos还可以替代springCloudConfig来完成配置中心功能,基础层面都通过DataIdGroup来定位配置内容

引入依赖

1
2
3
4
5
<!-- spring cloud alibaba nacos 配置-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
server:
port: 9001
spring:
application:
name: springcloudalibaba-provider-nacos
profiles:
active: dev
cloud:
nacos:
discovery:
server-addr: localhost:8848 #nacos注册中心地址
config:
file-extension: yaml #指定配置文件后缀
server-addr: localhost:8848 #nacos配置中心地址 文件名称为${spring.application.name}-${spring.profile.active}.${spring.cloud.config.file-extension}

management:
endpoints:
web:
exposure:
include: '*'

在Nacos中dataId组成部分为

1
2
3
4
5
6
7
${prefix}-${spring.profiles.active}.${file-extension}

prefix 默认为 spring.application.name 的值,也可以通过配置项 spring.cloud.nacos.config.prefix来配置

当 spring.profiles.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 ${prefix}.${file-extension},但是还是应该配置spring.profiles.active

file-exetension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置。目前只支持 properties 和 yaml 类型

该配置文件所对应的dataId为springcloudalibaba-provider-nacos-dev.yaml

Nacos添加配置

自动刷新

如果想要实现自动刷新,则在对应类上添加@RefreshScope注解

1
2
3
4
5
6
7
8
9
10
11
12
13
@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {

@Value("${config.value}")
private String value;

@RequestMapping("/get")
public String config(){
return value;
}
}

欢迎关注我的其它发布渠道