【SpringCloud】Nacos-02-配置管理
创建配置
一般对开关型配置进行配置,方便后面的热更新

统一配置管理
需要把nacos地址放入bootstrap.yml文件中,因为这个是优先级最高的。

- 将nacos的配置管理依赖导入
<!-- nacos配置管理依赖 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
- 在服务下面创建
bootstrap.yml引导配置文件,优先级高于application.yml
spring:
application:
name: userservice
profiles:
active: dev # 环境, 和name连起来,就是 userservice-dev
cloud:
nacos:
server-addr: localhost:8848 # nacos地址
config:
file-extension: yaml # 文件后缀名
- 编写测试代码,在
UserController中
@Value("${pattern.dateformat}")
private String dateformat;
@GetMapping("now")
public String now(){
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat));
}
通过/user/now返回的页面可以发现,确实读取到了nacos中的配置

配置热更新
nacos中的配置文件变更后,微服务无需重启就可以感知,不过需要通过下面两种配置实现:
两种方式
- 使用
@RefreshScope注解
在@Value注入的变量所在的类上添加该注解即可。 - 使用
@ConfigurationProperties注解
在PatternProperties中
@Data
@Component
@ConfigurationProperties(prefix = "pattern") // 指定属性前缀,自动拼接到成员变量上 pattern.*
public class PatternProperties {
private String dateformat; // pattern.dateformat
}
在UserController中
@Slf4j
@RestController
@RequestMapping("/user")
// @RefreshScope //方式1
public class UserController {
@Autowired
private UserService userService;
// @Value("${pattern.dateformat}")
// private String dateformat; //方式1
// 方式2
@Autowired
private PatternProperties properties;
@GetMapping("now")
public String now(){
// return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat)); //方式1
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(properties.getDateformat())); // 方式2
}
}
多环境配置共享
微服务启动过程时,会从nacos读取多个配置文件
- [spring.application.name]-[spring.profiles.active].yaml, 例如
userservice-dev.yaml - [spring.application.name].yaml, 例如
userservice.yaml
无论profile怎么变,[spring.application.name].yaml这个文件一定会加载,因此多环境共享配置,可以写入这个文件
多种配置优先级
userservice-dev.yaml > userservice.yaml > 本地配置

本文来自博客园,作者:chendsome,转载请注明原文链接:https://www.cnblogs.com/chendsome/p/18558977

浙公网安备 33010602011771号