持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第13天,点击查看活动详情
1 基础配置
Nacos不仅仅可以作为注册中心来使用,同时它支持作为配置中心来使用
1.1 pom文件加入依赖
这个依赖是专门作用于配置中心的
<dependency>
<groupId> com.alibaba.cloud </groupId>
<artifactId> spring-cloud-starter-alibaba-nacos-config </artifactId>
</dependency>
1.2 YML配置文件
springboot中配置文件的加载的时候,bootstrap优先级高于application,当一个项目启动之后,先读取bootstrap的配置信息,再读取application的配置信息。
这里引入bootstrap.yml配置作用是两个
- 让3377这个服务注册到Nacos中
- 去Nacos中去读取指定后缀为yaml的配置文件
1.2.1 bootstrap.yml
# nacos配置
server:
port: 3377
spring:
application:
name: nacos-config-client
cloud:
nacos:
discovery:
server-addr: localhost:8848 #Nacos服务注册中心地址
config:
server-addr: localhost:8848 #Nacos作为配置中心地址
file-extension: yaml #指定yaml格式的配置
1.2.2 application.yml
spring:
profiles:
active: dev # 表示开发环境
1.3 主启动类
@SpringBootApplication
@EnableDiscoveryClient
public class CloudalibabaConfig3377Application {
public static void main(String[] args) {
SpringApplication.run(CloudalibabaConfig3377Application.class, args);
}
}
1.4 业务类
@RefreshScope
的作用是实现配置自动更新,使配置文件中的配置修改后不用重启项目即生效
@RestController
@RefreshScope //支持Nacos的动态刷新功能
public class ConfigClientController {
@Value("${config.info}")
private String configInfo;
@GetMapping(value = "/config/info")
public String getConfigInfo(){
return configInfo;
}
}
2 Nacos配置命名规则
在 Nacos Spring Cloud 中,dataId
的完整格式如下
${prefix}-${spring.profiles.active}.${file-extension}
prefix
默认为spring.application.name
的值,也可以通过配置项spring.cloud.nacos.config.prefix
来配置。spring.profiles.active
即为当前环境对应的 profile,注意:当spring.profiles.active
为空时,对应的连接符-
也将不存在,dataId 的拼接格式变成${prefix}.${file-extension}
(不能删除)file-exetension
为配置内容的数据格式,可以通过配置项spring.cloud.nacos.config.file-extension
来配置。目前只支持properties
和yaml
类型。- 通过 Spring Cloud 原生注解
@RefreshScope
实现配置自动更新: - 所以根据官方给出的规则我们最终需要在Nacos配置中心添加的配置文件的名字规则和名字为:
${spring.application.name}-${spring.profiles.active}.${file-extension}
- nacos-config-client-dev.yaml
- 微服务名称-当前环境-文件格式
3 Nacos平台创建配置操作
3.1 增加配置
3.2 查看配置
测试
http://localhost:3377/config/info