目录

​​一、Nacos统一配置管理​​

​​二、配置自动刷新​​

​​方式一:在@Value注入的变量所在类上添加注解@RefreshScope​​

​​方式二:使用@ConfigurationProperties注解​​

​​三、多环境配置共享​​

​​三、多服务共享配置​​


一、Nacos统一配置管理

1、在Nacos同添加配置文件

Nacos配置管理-统一配置管理、配置自动刷新、多环境多服务共享配置_spring cloud

 2、在微服务中引入Nacos的配置管理客户端依赖:

<!--nacos的配置管理依赖-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

3、在userservice中的resource目录添加一个bootstrap.yml文件,这个文件是引导文件,优先级高于application.yml:

spring:
application:
name: userservice
profiles:
active: dev #环境
cloud:
nacos:
server-addr: localhost:80 # nacos地址
config:
file-extension: yaml # 文件后缀名

4、在user-service中将pattern.dateformat这个属性注入到UserController中做测试:

@RestController
@RequestMapping("/user")
public class UserController {

//注入nacos中的配置属性
@Value("${pattern.dateformat}")
private String dateformat;

//编写controller,通过日期格式化器来格式化现在的时间并返回
@GetMapping("now")
public String now(){
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(properties.getDateformat()));
}

//...略
}

二、配置自动刷新

Nacos中的配置文件变更后,微服务无需重启就可以感知,不过需要通过下面两种配置实现:

方式一:在@Value注入的变量所在类上添加注解@RefreshScope

@Slf4j
@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {

//注入nacos中的配置属性
@Value("${pattern.dateformat}")
private String dateformat;

方式二:使用@ConfigurationProperties注解

@Data
@Component
@ConfigurationProperties(prefix = "pattern")
public class PatternProperties {
private String dateformat;
}

注意事项:

不是多有的配置都适合放到配置中心,维护起来比较麻烦

建议将一些关键参数,需要运行时调整的参数放在nacos

三、多环境配置共享

微服务启动时会从nacos读取多个配置文件:

[spring.application.name]-[spring.profiles.active].yaml,例如:userservice-dev.yaml

[spring.appliction.name].yaml,例如:userservice.yaml

无论profile如何,[spring.appliction.name].yaml这个文件一定会加载,因此多环境共享配置可以写入这个文件

Nacos配置管理-统一配置管理、配置自动刷新、多环境多服务共享配置_配置管理_02

多种配置的优先级:

 

Nacos配置管理-统一配置管理、配置自动刷新、多环境多服务共享配置_nacos_03

三、多服务共享配置

不同微服务之间可以共享配置文件,通过下面的两种方式来指定

方式一:

spring:
application:
name: userservice
profiles:
active: dev #环境
cloud:
nacos:
server-addr: localhost:80 # nacos地址
config:
file-extension: yaml # 文件后缀名
shared-configs: # 多服务间共享的配置列表
-datald: common.yaml # 要共享的配置文件id

方式二:

spring:
application:
name: userservice
profiles:
active: dev #环境
cloud:
nacos:
server-addr: localhost:80 # nacos地址
config:
file-extension: yaml # 文件后缀名
extends-configs: # 多服务间共享的配置列表
-datald: extend.yaml # 要共享的配置文件id

多种配置的优先级:

Nacos配置管理-统一配置管理、配置自动刷新、多环境多服务共享配置_共享配置_04