使用nacos作为配置中心,在项目初始化时,要保证先从配置中心进行配置拉取,才能保证项目的正常启动
1、创建配置中心模块
pom
<!-- Nacos discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- Nacos config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
bootstarp.yml
server:
port: 3344
spring:
application:
name: nacos-config-client
cloud:
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
file-extension: yaml # 指定配置文件为yaml格式
group: DEV_GROUP
namespace: a06b3fe5-5be9-4e82-a56d-168afa4de85b
# DataId格式
# ${spring.application.name}-${spring.profile.active}-${spring.cloud.nacos.config.file-extension}
# nacos-config-client-dev.yaml
application.yml
spring:
profiles:
#active: info
#active: test
active: dev
启动类
@SpringBootApplication
@EnableDiscoveryClient
public class NacosConfigClientMain3344 {
public static void main(String[] args) {
SpringApplication.run(NacosConfigClientMain3344.class, args);
}
}
controller
@RestController
@RequestMapping("/config")
@RefreshScope //支持Nacos的动态刷新
public class ConfigController {
@Value("${config.info}")
private String configInfo;
@GetMapping("/info")
public String getConfigInfo(){
return configInfo;
}
}
2、Nacos配置规则
配置规则:即在客户端指定如何读取配置文件以及配置文件的命名规则
默认命名规则:
${prefix}-${spring.profile.active}.${file-extension}
# prefix
# 当前服务名称,也可以通过spring.cloud.nacos.config.prefix获取
# spring.profile.active
# 当前指定的开发环境
# file-extension
# 当前文件的格式,目前只支持yaml和properties
注:DataId配置文件名必须遵循配置规则中的命名方式
图片来源:尚硅谷 - 周阳 - Spring Cloud Alibaba
补充
nacos默认开启了自动刷新,更改配置文件,客户端读取的配置信息也随之改变(Nacos支持Bus消息总线,会自动发送命令更新信息)
3、配置分类
Namespace + Group + DataId
1、配置不同的DataId
# 通过yml配置读取指定的配置文件
spring:
profiles:
#active: info
#active: test
active: dev
2、配置不同的GroupId
3、配置不同的Namespace
# 客户端yml配置不同的namespace
server:
port: 3344
spring:
application:
name: nacos-config-client
cloud:
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
file-extension: yaml # 指定配置文件为yaml格式
group: DEV_GROUP
namespace: a06b3fe5-5be9-4e82-a56d-168afa4de85b
评论 (0)