1、pom依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
2、配置文件
spring:
application:
name: nacos-config
## 当前环境,这个和dataId有关-> ${prefix}-${spring.profiles.active}.${file-extension}
profiles:
active: dev
cloud:
nacos:
config:
## nacos的地址,作为配置中心
server-addr: 127.0.0.1:8848
## 配置内容的数据格式,目前只支持 properties 和 yaml 类型,这个和dataId有关-> ${prefix}-${spring.profiles.active}.${file-extension}
file-extension: properties
management:
endpoints:
web:
exposure:
## yml文件中存在特殊字符,必须用单引号包含,否则启动报错
include: '*'
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 类型。
//实体类注解正常使用
@Component
@Data
public class DynamicConfigEntity {
//直接读取nacos中config.version的配置
@Value("${config.version}")
private String version;
}
注意:DataId一定要带有后缀properties或者yml
3、动态刷新
@RefreshScope
@Component
@RefreshScope
@Data
public class DynamicConfigEntity {
//直接读取nacos中config.version的配置
@Value("${config.version}")
private String version;
}
设置refresh: true
spring:
application:
name: nacos-config-share
cloud:
nacos:
config:
## 指定配置文件的分组,默认是DEFAULT_GROUP
group: ORDER_GROUP
refresh: true
4、多环境隔离
namespace 隔离生产、测试、开发环境
命名空间ID是系统自动生成的唯一ID
spring:
application:
name: nacos-config
cloud:
nacos:
config:
## namespace的取值是命名空间ID,这里取的是test命名空间ID
namespace: d0ffeec2-3deb-4540-9664-fdd77461fd6b
注意:Namespace必须在bootstrap.yml配置文件中指定,否则不生效。
5、多业务隔离Group
spring:
application:
name: nacos-config
cloud:
nacos:
config:
## 指定命名空间
namespace: d0ffeec2-3deb-4540-9664-fdd77461fd6b
## 指定分组为ORDER_GROUP
group: ORDER_GROUP
注意:Group配置和Namespace一样,要在bootstrap.yml文件中配置。