背景
前面我们整合了Nacos Config,并验证了动态配置刷新的效果了,现在我们来进一步学习一下Nacos Config的多环境配置和通用环境配置相关的内容
环境
Windows10
JDK1.8
IDEA2021
Maven2.6
下载安装Nacos
修改配置
基于上文的项目,进行修改
YML
spring:
application:
name: nacos-config
cloud:
nacos:
config:
server-addr: localhost:8848
file-extension: yml
profiles:
active: prod
Nacos配置
注:Data Id = spring.application.name + [-spring.profile.active]. + file-extension
测试
下面从Nacos的不同环境配置进一步了解Nacos Config
生产环境
YML配置如上
启动项目,浏览器输入接口地址
测试环境
修改YML配置
spring:
application:
name: nacos-config
cloud:
nacos:
config:
server-addr: localhost:8848
file-extension: yml
profiles:
active: test
Nacos新增test环境
配置
重启项目
浏览器输入接口地址
公共环境
YML
spring:
application:
name: nacos-config
cloud:
nacos:
config:
server-addr: localhost:8848
file-extension: yml
profiles:
active: test
Nacos新建公共配置,Data Id以spring.application.name命名
通用配置内容
修改接口,我们看是否能够在test环境
下同时访问到通用配置
内容
package com.nacos.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class NacosConfigController {
@Value("${str}")
private String str;
@Value("${commonStr}")
private String commonStr;
@GetMapping("/")
public String getConfig() {
return str;
}
@GetMapping("/common")
public String getCommonConfig() {
return commonStr;
}
}
重启服务,访问接口地址
- 测试环境配置
- 公共环境配置
小结:即使是在测试环境下,也可以获取到公共的配置
共享环境
如果是想要用到其他的Nacos配置文件,要怎么处理?
下面在Nacos新建两个配置文件,如下
- 共享Redis配置
- 共享MQ配置
修改YML
spring:
application:
name: nacos-config
cloud:
nacos:
config:
server-addr: localhost:8848
file-extension: yml
shared-configs[0]:
data_id: redis.yml
refresh: true
shared-configs[1]:
data_id: mq.yml
refresh: true
profiles:
active: test
修改接口,添加获取Redis和mq的接口
package com.nacos.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class NacosConfigController {
@Value("${str}")
private String str;
@Value("${commonStr}")
private String commonStr;
@Value("${redis}")
private String redis;
@Value("${mq}")
private String mq;
@GetMapping("/")
public String getConfig() {
return str;
}
@GetMapping("/common")
public String getCommonConfig() {
return commonStr;
}
@GetMapping("/redis")
public String getRedisConfig() {
return redis;
}
@GetMapping("/mq")
public String getMqCommonConfig() {
return mq;
}
}
重启项目,浏览器输入对应接口地址
- redis
- mq
小结:在test环境下可以通过shared-configs[0]
或者extension-configs[0]
配置多个其他配置文件