配置管理

1. 添加依赖

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

2. 配置

application.yml 中配置 Nacos Server 的地址和应用名:

spring:
  application:
    name: @artifactId@
  profiles:
    active: @profiles.active@

---
spring:
  config:
    import: nacos:${spring.application.name}.${spring.cloud.nacos.config.file-extension}?refresh=true
  cloud:
    nacos:
      config:
        username: nacos
        password: nacos
        server-addr: @nacos.addr@
        file-extension: yml
        namespace: @nacos.namespace@

spring.application.name 是构成 Nacos 配置管理 dataId 字段的一部分。

注意

3. 通过注解 @RefreshScope 实现配置自动更新

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

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

    @RequestMapping("/get")
    public boolean get() {
        return useLocalCache;
    }
}

注意

如果想要完整地利用 nacos 相关的配置,必须将所有配置放在 bootstrap.ymlbootstrap.properties 文件中,并且必须引入 bootstrap 相关依赖(或者通过将系统环境变量 spring.cloud.bootstrap.enabled 设为 true):

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

只有这样,才能够省略 spring.config.import 配置,进而充分利用 nacos 特定的配置。

spring cloud config 文档中的原文如下:

Unless you are using config first bootstrap, you will need to have a spring.config.import property in your configuration properties with an optional: prefix. For example:

spring.config.import=optional:configserver:

Config First Bootstrap

To use the legacy bootstrap way of connecting to Config Server, bootstrap must be enabled via a property or the spring-cloud-starter-bootstrap starter. The property is spring.cloud.bootstrap.enabled=true. It must be set as a System Property or environment variable.

Last updated