Spring Cloud Config 客户端

Spring Boot 应用程序可以直接利用 Spring Config Server(或应用程序开发者提供的其他外部属性源)的优势。它还获得了一些与 Environment 更改事件相关的额外有用特性。

Spring Boot Config Data 导入

Spring Boot 2.4 引入了一种通过 spring.config.import 属性导入配置数据的新方式。这现在是绑定到 Config Server 的默认方式。

要选择性地连接到 Config Server,请在 application.properties 中设置以下内容

application.properties
spring.config.import=optional:configserver:

这将连接到默认位置 "http://localhost:8888" 的 Config Server。移除 optional: 前缀将导致 Config Client 在无法连接到 Config Server 时失败。要更改 Config Server 的位置,可以设置 spring.cloud.config.uri 或将 URL 添加到 spring.config.import 语句中,例如 spring.config.import=optional:configserver:http://myhost:8888。import 属性中的位置优先于 uri 属性。

Spring Boot Config Data 通过两个步骤解析配置。首先,它使用 default 配置文件加载所有配置。这使得 Spring Boot 可以收集所有可能激活任何额外配置文件的配置。在收集所有激活的配置文件后,它将加载活动配置文件的任何额外配置。因此,您可能会看到向 Spring Cloud Config Server 发送多个请求以获取配置。这是正常的,也是在使用 spring.config.import 时 Spring Boot 加载配置的方式的副作用。在 Spring Cloud Config 的早期版本中,只进行一次请求,但这表示您无法从 Config Server 的配置中激活配置文件。现在通过仅包含 default 配置文件的额外请求,这成为了可能。

通过 spring.config.import 进行 Spring Boot Config Data 导入的方��不需要 bootstrap 文件(properties 或 yaml)。

配置优先 Bootstrap

要使用传统的 bootstrap 方式连接到 Config Server,必须通过属性或 spring-cloud-starter-bootstrap 启动器启用 bootstrap。属性为 spring.cloud.bootstrap.enabled=true。它必须设置为系统属性或环境变量。启用 bootstrap 后,任何类路径中包含 Spring Cloud Config Client 的应用程序都将按如下方式连接到 Config Server:Config client 启动时,它会绑定到 Config Server(通过 spring.cloud.config.uri bootstrap 配置属性)并使用远程属性源初始化 Spring Environment

这种行为的最终结果是,所有想要使用 Config Server 的客户端应用程序都需要一个 bootstrap.yml(或环境变量),并在其中设置 spring.cloud.config.uri 中的服务器地址(默认为 "http://localhost:8888")。

发现优先查找

除非您使用配置优先 Bootstrap,否则您需要在配置属性中使用 optional: 前缀设置 spring.config.import 属性。例如,spring.config.import=optional:configserver:

如果您使用 DiscoveryClient 实现,例如 Spring Cloud Netflix 和 Eureka Service Discovery 或 Spring Cloud Consul,您可以让 Config Server 在 Discovery Service 中注册。

如果您更喜欢使用 DiscoveryClient 来定位 Config Server,您可以通过设置 spring.cloud.config.discovery.enabled=true(默认为 false)来实现。例如,对于 Spring Cloud Netflix,您需要定义 Eureka 服务器地址(例如,在 eureka.client.serviceUrl.defaultZone 中)。使用此选项的代价是在启动时需要额外的网络往返来定位服务注册。好处是,只要 Discovery Service 是一个固定点,Config Server 就可以更改其坐标。默认的服务 ID 是 configserver,但您可以在客户端通过设置 spring.cloud.config.discovery.serviceId(以及在服务器上,以服务通常的方式,例如通过设置 spring.application.name)来更改它。

发现客户端实现都支持某种元数据映射(例如,Eureka 有 eureka.instance.metadataMap)。Config Server 的一些额外属性可能需要在其服务注册元数据中配置,以便客户端能够正确连接。如果 Config Server 使用 HTTP Basic 保护,您可以将凭据配置为 userpassword。此外,如果 Config Server 有一个上下文路径,您可以设置 configPath。例如,以下 YAML 文件适用于作为 Eureka 客户端的 Config Server

eureka:
  instance:
    ...
    metadataMap:
      user: osufhalskjrtl
      password: lviuhlszvaorhvlo5847
      configPath: /config

使用 Eureka 和 WebClient 的发现优先 Bootstrap

如果您使用 Spring Cloud Netflix 的 Eureka DiscoveryClient,并且还想使用 WebClient 而不是 Jersey 或 RestTemplate,您需要在类路径中包含 WebClient,并设置 eureka.client.webclient.enabled=true

Config 客户端快速失败

在某些情况下,如果服务无法连接到 Config Server,您可能希望其启动失败。如果这是期望的行为,请设置 bootstrap 配置属性 spring.cloud.config.fail-fast=true,使客户端抛出异常并停止。

要使用 spring.config.import 获得类似的功能,只需省略 optional: 前缀。

Config 客户端重试

如果您预计 config server 在应用程序启动时可能偶尔不可用,您可以让它在失败后继续尝试。首先,您需要设置 spring.cloud.config.fail-fast=true。然后您需要在类路径中添加 spring-retryspring-boot-starter-aop。默认行为是重试六次,初始回退间隔为 1000ms,后续回退使用 1.1 的指数乘数。您可以通过设置 spring.cloud.config.retry.* 配置属性来配置这些属性(及其他属性)。要使用随机指数回退策略,请将 spring.cloud.config.retry.useRandomPolicy 设置为 true

spring.cloud.config.retry.useRandomPolicytrue 时,即使使用随机指数回退策略,max-attemptsinitial-intervalmax-intervalmultiplier 属性仍会生效。关于它们如何使用的详细信息可以在 Spring Retry 中的 ExponentialRandomBackOffPolicyExponentialBackOffPolicy 中找到。
要完全控制重试行为并使用传统的 bootstrap,请添加一个类型为 RetryOperationsInterceptor 且 ID 为 configServerRetryInterceptor@Bean。Spring Retry 有一个 RetryInterceptorBuilder 支持创建此类 Bean。

使用 spring.config.import 的 Config 客户端重试

重试功能适用于 Spring Boot 的 spring.config.import 语句和常规属性。但是,如果 import 语句位于配置文件中,例如 application-prod.properties,那么您需要不同的方式来配置重试。配置需要作为 URL 参数放置在 import 语句上。

application-prod.properties
spring.config.import=configserver:http://configserver.example.com?fail-fast=true&max-attempts=10&max-interval=1500&multiplier=1.2&initial-interval=1100"

这会设置 spring.cloud.config.fail-fast=true(注意上面缺少前缀),以及所有可用的 spring.cloud.config.retry.* 配置属性。

定位远程配置资源

Config Service 从 /{application}/{profile}/{label} 提供属性源,客户端应用程序中的默认绑定如下

  • "application" = ${spring.application.name}

  • "profile" = ${spring.profiles.active} (实际上是 Environment.getActiveProfiles())

  • "label" = "master"

设置属性 ${spring.application.name} 时,请勿在应用程序名称前加上保留字 application-,以避免解析到错误的属性源。

您可以通过设置 spring.cloud.config.*(其中 *nameprofilelabel)来覆盖所有这些值。label 对于回滚到以前的配置版本非常有用。对于默认的 Config Server 实现,它可以是 git 标签、分支名称或提交 ID。Label 也可以提供为逗号分隔的列表。当处理特性分支时,这种行为非常有用。例如,您可能希望将 config label 与您的分支对齐,但使其成为可选的(在这种情况下,请使用 spring.cloud.config.label=myfeature,develop)。

请求多个标签

在 Spring Cloud Config 4.2.0 之前,如果您将 spring.cloud.config.label 设置为逗号分隔的标签列表,Config Client 会尝试通过向 Config Server 发出请求来逐个尝试每个标签,直到找到一个可用的标签。这意味着如果找到第一个标签,后续标签将不再尝试。

自 Spring Cloud Config 4.2.0 起,如果您将 spring.cloud.config.label 设置为逗号分隔的标签列表并且设置 spring.cloud.config.send-all-labels,Config Client 将使用逗号分隔的标签列表向 Config Server 发出单个请求,如果 CONFIG SERVER 使用 4.2.0 或更高版本,它将返回一个包含所有标签属性源的单个响应。

spring.cloud-config.send-all-labels 设置为 true,将 spring.cloud.config.label 设置为逗号分隔的标签列表,并使用早于 4.2.0 版本的 Config Server 将导致意外行为,因为 Config Server 会尝试查找与逗号分隔列表值匹配的标签,而不会尝试拆分标签。

通过在单个请求中发送所有标签,可以减少向 Config Server 发出的请求数量。

spring.cloud.config.send-all-labels 默认设置为 false,因此旧的行为仍然是默认行为,并且它还保持与旧版本 Config Server 的兼容性。

指定 Config Server 的多个 URL

为了在高可用性部署多个 Config Server 实例并预计一个或多个实例有时不可用或无法响应请求(例如 Git 服务器宕机),您可以指定多个 URL(在 spring.cloud.config.uri 属性下以逗号分隔的列表形式)或者让所有实例在 Eureka 等服务注册中心注册(如果使用发现优先 Bootstrap 模式)。

spring.cloud.config.uri 下列出的 URL 将按列表中的顺序尝试。默认情况下,Config Client 会尝试从每个 URL 获取属性,直到尝试成功以确保高可用性。

但是,如果您只想在 Config Server 未运行时(即应用程序已退出)或发生连接超时时确保高可用性,请将 spring.cloud.config.multiple-uri-strategy 设置为 connection-timeout-only。(spring.cloud.config.multiple-uri-strategy 的默认值为 always。)例如,如果 Config Server 返回 500(内部服务器错误)响应,或 Config Client 从 Config Server 收到 401(由于凭据错误或其他原因),Config Client 不会尝试从其他 URL 获取属性。400 错误(可能除了 404)表示用户问题而不是可用性问题。请注意,如果 Config Server 设置为使用 Git 服务器且调用 Git 服务器失败,可能会发生 404 错误。

可以在单个 spring.config.import 键下指定多个位置,而不是使用 spring.cloud.config.uri。位置将按照它们定义的顺序处理,后导入的优先。但是,如果 spring.cloud.config.fail-fasttrue,如果第一次调用 Config Server 因任何原因失败,Config Client 将失败。如果 fail-fastfalse,它将尝试所有 URL,直到一次调用成功为止,无论失败原因如何。(在使用 spring.config.import 下指定 URL 时,spring.cloud.config.multiple-uri-strategy 不适用。)

如果您在 Config Server 上使用 HTTP basic security,目前只有在您将凭据嵌入到您在 spring.cloud.config.uri 属性下指定的每个 URL 中时,才可能支持每个 Config Server 的身份验证凭据。如果您使用任何其他类型的安全机制,您目前无法支持每个 Config Server 的身份验证和授权。

配置超时

如果您想配置超时阈值

  • 可以通过使用属性 spring.cloud.config.request-read-timeout 来配置读取超时。

  • 可以通过使用属性 spring.cloud.config.request-connect-timeout 来配置连接超时。

配置字符集

如果您想配置服务器应提供的特定字符集,您需要通过 charset 应用它。

spring:
  cloud:
    config:
      charset: UTF-8

字符集配置属性定义为 java.nio.charset.Charset

安全

如果在服务器上使用 HTTP Basic security,客户端需要知道密码(如果不是默认用户,还需要知道用户名)。您可以通过 config server URI 或通过单独的 username 和 password 属性来指定用户名和密码,如下例所示

spring:
  cloud:
    config:
     uri: https://user:[email protected]

以下示例显示了传递相同信息的另一种方式

spring:
  cloud:
    config:
     uri: https://myconfig.mycompany.com
     username: user
     password: secret

spring.cloud.config.passwordspring.cloud.config.username 的值会覆盖 URI 中提供的任何内容。

如果您在 Cloud Foundry 上部署应用程序,提供密码的最佳方式是通过服务凭据(例如在 URI 中,因为它不需要在配置文件中)。以下示例在本地和 Cloud Foundry 上名为 configserver 的用户提供服务中都适用

spring:
  cloud:
    config:
     uri: ${vcap.services.configserver.credentials.uri:http://user:password@localhost:8888}

如果 config server 需要客户端 TLS 证书,您可以通过属性配置客户端 TLS 证书和信任库,如下例所示

spring:
  cloud:
    config:
      uri: https://myconfig.myconfig.com
      tls:
        enabled: true
        key-store: <path-of-key-store>
        key-store-type: PKCS12
        key-store-password: <key-store-password>
        key-password: <key-password>
        trust-store: <path-of-trust-store>
        trust-store-type: PKCS12
        trust-store-password: <trust-store-password>

需要将 spring.cloud.config.tls.enabled 设置为 true 以启用 config 客户端 TLS。省略 spring.cloud.config.tls.trust-store 时,使用 JVM 默认信任库。spring.cloud.config.tls.key-store-typespring.cloud.config.tls.trust-store-type 的默认值为 PKCS12。省略密码属性时,假定为空密码。

如果您使用另一种安全形式,您可能需要为 ConfigServicePropertySourceLocator提供一个 RestTemplate(例如,在 bootstrap 上下文中获取并注入它)。

健康指示器

Config Client 提供了一个 Spring Boot 健康指示器,它尝试从 Config Server 加载配置。可以通过设置 health.config.enabled=false 来禁用健康指示器。响应也会被缓存以提高性能。默认的缓存生存时间为 5 分钟。要更改此值,请设置 health.config.time-to-live 属性(以毫秒为单位)。

提供自定义 RestTemplate

在某些情况下,您可能需要自定义客户端向 config server 发出的请求。通常,这涉及传递特殊的 Authorization 头以验证对服务器的请求。

使用 Config Data 提供自定义 RestTemplate

在使用 Config Data 时提供自定义 RestTemplate

  1. 创建一个实现 BootstrapRegistryInitializer 的类

    CustomBootstrapRegistryInitializer.java
    public class CustomBootstrapRegistryInitializer implements BootstrapRegistryInitializer {
    
    	@Override
    	public void initialize(BootstrapRegistry registry) {
    		registry.register(RestTemplate.class, context -> {
    			RestTemplate restTemplate = new RestTemplate();
    			// Customize RestTemplate here
    			return restTemplate;
    		});
    	}
    
    }
  2. resources/META-INF 中,创建一个名为 spring.factories 的文件,并指定您的自定义配置,如下例所示

    spring.factories
    org.springframework.boot.BootstrapRegistryInitializer=com.my.config.client.CustomBootstrapRegistryInitializer

使用 Bootstrap 提供自定义 RestTemplate

在使用 Bootstrap 时提供自定义 RestTemplate

  1. 创建一个新的配置 Bean,实现 PropertySourceLocator,如下例所示

    CustomConfigServiceBootstrapConfiguration.java
    @Configuration
    public class CustomConfigServiceBootstrapConfiguration {
        @Bean
        public ConfigServicePropertySourceLocator configServicePropertySourceLocator() {
            ConfigClientProperties clientProperties = configClientProperties();
           ConfigServicePropertySourceLocator configServicePropertySourceLocator =  new ConfigServicePropertySourceLocator(clientProperties);
            configServicePropertySourceLocator.setRestTemplate(customRestTemplate(clientProperties));
            return configServicePropertySourceLocator;
        }
    }
    要简化添加 Authorization 头的方法,可以使用 spring.cloud.config.headers.* 属性代替。
  2. resources/META-INF 中,创建一个名为 spring.factories 的文件,并指定您的自定义配置,如下例所示

    spring.factories
    org.springframework.cloud.bootstrap.BootstrapConfiguration = com.my.config.client.CustomConfigServiceBootstrapConfiguration

Vault

将 Vault 用作 config server 的后端时,客户端需要提供一个 token 供服务器从 Vault 中检索值。可以在客户端通过在 bootstrap.yml 中设置 spring.cloud.config.token 来提供此 token,如下例所示

spring:
  cloud:
    config:
      token: YourVaultToken

Vault 中的嵌套密钥

Vault 支持在存储在 Vault 中的值内嵌套密钥的功能,如下例所示

echo -n '{"appA": {"secret": "appAsecret"}, "bar": "baz"}' | vault write secret/myapp -

此命令将一个 JSON 对象写入您的 Vault。要在 Spring 中访问这些值,您将使用传统的点(.)注解,如下例所示

@Value("${appA.secret}")
String name = "World";

上面的代码会将 name 变量的值设置为 appAsecret

AOT 和 Native Image 支持

4.0.0 起,Spring Cloud Config Client 支持 Spring AOT 转换和 GraalVM native images。

配置优先 Bootstrap(使用 spring.config.use-legacy-processing=true)不支持 AOT 和 native image。
Native image 不支持 refresh scope。如果您打算将 config client 应用程序作为 native image 运行,请确保将 spring.cloud.refresh.enabled 属性设置为 false
构建包含 Spring Cloud Config Client 的项目时,必须确保其连接的配置数据源(例如 Spring Cloud Config Server、Consul、Zookeeper、Vault 等)可用。例如,如果您从 Spring Cloud Config Server 检索配置数据,请确保其实例正在运行并可在 Config Client 设置中指示的端口访问。这是必要的,因为应用程序上下文在构建时进行了优化,需要解析目标环境。
由于在 AOT 和 native 模式下,配置在构建时进行处理和上下文进行优化,因此任何影响 bean 创建的属性(例如 bootstrap 上下文中的属性)在构建时和运行时应设置为相同的值,以避免意外行为。
由于 Config Client 在从 native image 启动时会连接到运行的数据源(例如 Config Server),快速启动时间会因网络通信所需的时间而变慢。

附录

可观测性元数据

可观测性 - 指标

您可以在下方找到此项目声明的所有指标列表。

环境仓库

在 EnvironmentRepository 周围创建的观测。

指标名称 spring.cloud.config.environment.find(由约定类 org.springframework.cloud.config.server.environment.ObservationEnvironmentRepositoryObservationConvention 定义)。类型 timer

指标名称 spring.cloud.config.environment.find.active(由约定类 org.springframework.cloud.config.server.environment.ObservationEnvironmentRepositoryObservationConvention 定义)。类型 long task timer

在启动观测后添加的 KeyValues 可能在 *.active 指标中缺失。
Micrometer 内部使用 nanoseconds 作为基本单位。但是,每个后端决定实际的基本单位。(即 Prometheus 使用 seconds)

包含类的完全限定名 org.springframework.cloud.config.server.environment.DocumentedConfigObservation

所有标签必须以 spring.cloud.config.environment 前缀开头!
表 1. 低基数键

名称

描述

spring.cloud.config.environment.application (必填)

查询属性的应用程序名称。

spring.cloud.config.environment.class (必填)

EnvironmentRepository 的实现。

spring.cloud.config.environment.label (必填)

查询属性的标签。

spring.cloud.config.environment.profile (必填)

查询属性的应用程序名称。

可观测性 - Span

您可以在下方找到此项目声明的所有 span 列表。

环境仓库 Span

在 EnvironmentRepository 周围创建的观测。

Span 名称 spring.cloud.config.environment.find(由约定类 org.springframework.cloud.config.server.environment.ObservationEnvironmentRepositoryObservationConvention 定义)。

包含类的完全限定名 org.springframework.cloud.config.server.environment.DocumentedConfigObservation

所有标签必须以 spring.cloud.config.environment 前缀开头!
表 2. 标签键

名称

描述

spring.cloud.config.environment.application (必填)

查询属性的应用程序名称。

spring.cloud.config.environment.class (必填)

EnvironmentRepository 的实现。

spring.cloud.config.environment.label (必填)

查询属性的标签。

spring.cloud.config.environment.profile (必填)

查询属性的应用程序名称。