Nacos配置管理

Nacos配置管理

统一配置管理

在Nacos中添加配置文件*(名称-环境.文件格式)*

测试:

配置内容

  pattern:
    dateformat: MM-dd HH:mm:ss:SSS

image-20220813143429457

1.引入Nacos的配置管理客户端依赖

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

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

spring:
  application:
    name: userservice

  profiles:
    active: dev  #环境

  cloud:
    nacos:
      server-addr: localhost:8848  #nacos地址
      config:
        file-extension: yaml  #文件后缀名

3.测试,获取配置文件中的日期格式

@Value("${pattern.dateformat}")
private String dataformate;

@GetMapping("now")
public String now(){
    return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dataformate));
}

image-20220813145434629

配置热更新

Nacos中的配置文件变更后,微服务无需重启就能感知。

方式一:

在@Value注入的变量所在类上添加注解@RefreshScope

image-20220813145827397

在这里插入图片描述

方式二:使用@ConfigurationProperties注解

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

}
@Autowired
private PatternProperties patternProperties;

@GetMapping("now")
public String now(){
    return LocalDateTime.now().format(DateTimeFormatter.ofPattern(patternProperties.getDateformat()));
}

多环境配置共享

无论环境如何变化,userservice.yaml一定会加载

image-20220813151256269

测试:

在ParrernProperties类中

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

    private String envSharedValue;
}

展示到页面上

@GetMapping("prop")
public String prop(){
    return patternProperties.getEnvSharedValue();
}

image-20220813151247921

多种配置的优先级

服务名-profiole.yaml>服务名称.yaml>本地配置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值