本地文件系统

1. 修改 application.yml

在 application.yml 文件中增加相关配置信息,包括:

  • spring.profiles.active=native

  • spring.cloud.config.server.native.search-locations=classpath:/config

server:
  port: 8071
spring:
  application:
    name: config-server
  profiles:
    active: native
  cloud:
    config:
      server:
        native:
          search-locations: classpath:/config

classpath 属性使得 Spring Cloud Config 服务器端在 src/main/resources/config 文件夹中查找配置数据。

2. 创建服务的配置文件

为以下 3 个环境创建应用程序配置数据:默认环境开发环境生产环境

应用程序配置文件的命名约定是“应用程序名称-环境名称.properties”或“应用程序名称-环境名称.yml”。环境名称由在服务启动时命令行传入的 Spring Boot 的 profile 指定。

src/main/resources/config 文件夹分别创建了三个文件:

  • license-service.yml

  • license-service-dev.yml

  • license-service-prod.yml:

3. 启动 Config Server

通过 REST 接口获取不同环境的配置信息:

http://localhost:8071/license-service/default
http://localhost:8071/license-service/dev
http://localhost:8071/license-service/prod

仔细观察,会看到在选择 dev 端点时,Spring Cloud Config 服务器端返回的是默认配置开发环境下的配置

Spring Cloud Config 返回两组配置信息的原因是:Spring 框架实现了一种用于解决问题的层次结构机制。当 Spring 框架解决问题时,它将先查找默认属性文件中定义的属性,然后用特定环境的值(如果存在)去覆盖默认值。

Last updated