Spring boot 2.4.x 无法处理来自配置服务器的多文档 yml 文件

问题描述

  1. Java 版本:8
  2. Spring Boot 版本:2.4.1
  3. Spring Cloud 版本:2020.0.0,具体我使用的是连接到 GIT 的 Spring Cloud Config Server,我们的服务是 Spring Cloud Config Clients。

我已不再使用 bootstrap.yml 并开始使用文档 herehere

中提到的 spring.config.importspring.config.activate.on-profile

我在我的服务中的配置,它是配置服务器的客户端,如下所示:

server.port: 9001
spring:
  application.name: my-rest-service
  config.import: configserver:http://localhost:8888
  cloud.config.profile: ${spring.profiles.active}

我在配置服务器中的配置如下所示:

application.yml(有两个文件以 --- 分隔)

logging:
  file.name: <omitted>
  level:
    root: INFO
---
spring:
  config.activate.on-profile: dev
  logging.level.root: DEBUG

my-rest-sercive.yml(有两个文件以 --- 分隔)

spring:
  datasource:
    driver-class-name: <omitted>
    username: <omitted>
    password: <omitted>
---
spring:
  config.activate.on-profile: dev
  datasource.url: <omitted>

因为有一个配置文件“dev”处于活动状态,我成功地从配置服务器获取了以下 4 个配置:

  • application.yml:一般日志记录级别
  • application.yml:dev 的特定日志记录
  • my-rest-sercive.yml:一般数据源属性
  • my-rest-sercive.yml:dev 的特定数据源网址

当我使用浏览器或调试时或在降低日志级别进行跟踪时,我可以看到这 4 个源被成功获取

o.s.b.c.config.ConfigDataEnvironment     : Adding imported property source 'configserver:https://git.company.com/path.git/file:C:\configservergit\config\my-rest-service.yml'
o.s.b.c.config.ConfigDataEnvironment     : Adding imported property source 'configserver:https://git.company.com/path.git/file:C:\configservergit\config\my-rest-service.yml'
o.s.b.c.config.ConfigDataEnvironment     : Adding imported property source 'configserver:https://git.company.com/path.git/file:C:\configservergit\config\application.yml'
o.s.b.c.config.ConfigDataEnvironment     : Adding imported property source 'configserver:https://git.company.com/path.git/file:C:\configservergit\config\application.yml'

但是,请注意,因为我使用多文档 yml 文件,所以在这 4 个属性源中只使用了两个唯一名称

在后面的步骤中,当 Spring 创建数据源 bean 时,他抱怨找不到数据源 URL。如果我调试 spring bean 工厂,我确实可以看到在配置服务器返回的 4 个属性文件中,只剩下两个(不包含开发配置文件特定配置的那些)。我认为这是因为它们具有相同的名称并且它们相互覆盖。这是MutablePropertySource.class中这段代码效果

public void addLast(PropertySource<?> propertySource) {
    synchronized(this.propertySourceList) {
        this.removeIfPresent(propertySource); <-- this is the culrprit!
        this.propertySourceList.add(propertySource);
    }
} 

这是从 Spring 2.3/Spring Cloud Hoxton 正确收集所有属性的重大更改。我认为 spring cloud 需要更改配置服务器,以便 yml 中的每个文档在返回 Spring 时都有一个唯一的名称。这正是 Spring Boot 处理多文档 yml 文件的方式,通过将字符串 (documenyt #1) 附加到属性名称

我发现 an interesting note 关于配置文件和多文档 yml,基本上说它不受支持,但这不适用于我的用例,因为我的 yml 文件不是基于配置文件的(没有 {{1} } 在文件名的最后一部分)。

解决方法

这是新版本的一个已知问题。我们可以在 the spring cloud config server github page 上跟踪问题。

解决方法似乎是停止使用多文档 yml 文件,并使用文件名中包含配置文件名称的多个不同文件。