SpringCloud_Alibaba

九、通过Nacos进行服务配置

2020-12-15  本文已影响0人  轻轻敲醒沉睡的心灵

Nacos服务注册发现参考:https://www.jianshu.com/p/ba298e0a2eab

1. 服务中引入Nacos配置包

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

2. 本地bootstrap.yml(bootstrap.properties)增加配置

# spring
spring: 
  profiles:
    active: dev
  # 服务名称必须带上,不然nacos服务列表中没有,也不会有注册成功的信息
  application:
    name: car-management-service-dict
  cloud:
    nacos:
      # 服务注册发现
      discovery:
        server-addr: www.baidu.com:8848
      # 服务配置
      config:
        server-addr: www.baidu.com:8848
        file-extension: yaml

3. 在nacos中添加配置

Nacos新增配置图

4. 配置自动更新

使用Spring Cloud 原生注解 @RefreshScope,这样通过@Value注解取到的值是更新过的(@ConfigProperties注解不是)

@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {

  @Value("${useLocalCache:false}")
  private boolean useLocalCache;

  @RequestMapping("/get")
  public boolean get() {
      return useLocalCache;
  }
}
上一篇 下一篇

猜你喜欢

热点阅读