Spring Cloud Config 客户端

Spring Boot 应用程序可以立即利用 Spring Config Server(或应用程序开发人员提供的其他外部属性源)。 它还提供了一些与Environment更改事件。spring-doc.cadn.net.cn

Spring Boot Config 数据导入

Spring Boot 2.4 引入了一种通过spring.config.import财产。这是绑定到 Config Server 的默认方式。spring-doc.cadn.net.cn

要选择性地连接到 config server,请在 application.properties 中设置以下内容:spring-doc.cadn.net.cn

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-doc.cadn.net.cn

Spring Boot Config Data 通过两步过程解析配置。首先,它使用default轮廓。这允许 Spring Boot 收集所有可能激活任何其他配置文件的配置。 收集完所有已激活的配置文件后,它将加载活动配置文件的任何其他配置。 因此,您可能会看到向 Spring Cloud Config Server 发出多个请求以获取配置。这 是正常的,并且是 Spring Boot 在使用spring.config.import.在上一个 版本的 Spring Cloud Config 中,只发出了一个请求,但这意味着您无法激活配置文件 来自来自 Config Server 的配置。现在,仅包含 'default' 配置文件的附加请求会发出 这是可能的。spring-doc.cadn.net.cn

一个bootstrap文件(properties 或 yaml)不需要 Spring Boot Config Data 方法的导入方式spring.config.import.

Config First 引导

要使用传统的引导方式连接到 Config Server,必须通过属性或spring-cloud-starter-bootstrap起动机。该属性为spring.cloud.bootstrap.enabled=true.它必须设置为 System Property 或 environment variable。 启用 bootstrap 后,在 Classpath 上具有 Spring Cloud Config Client 的任何应用程序都将连接到 Config Server,如下所示: 当配置客户端启动时,它会绑定到配置服务器(通过spring.cloud.config.uribootstrap 配置属性)并初始化 SpringEnvironment与远程属性源一起使用。spring-doc.cadn.net.cn

此行为的最终结果是,所有想要使用 Config Server 的客户端应用程序都需要一个bootstrap.yml(或环境变量),并将服务器地址设置为spring.cloud.config.uri(默认为 “http://localhost:8888”)。spring-doc.cadn.net.cn

Discovery 首次查找

除非您使用 config first 引导,否则您需要有一个spring.config.import属性中带有optional:前缀。 例如spring.config.import=optional:configserver:.

如果您使用DiscoveryClient实施,例如 Spring Cloud Netflix 和 Eureka Service Discovery 或 Spring Cloud Consul,您可以让 Config Server 向 Discovery Service 注册。spring-doc.cadn.net.cn

如果您更喜欢使用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).spring-doc.cadn.net.cn

发现客户端实现都支持某种元数据映射(例如,我们有eureka.instance.metadataMap尤里卡)。 可能需要在其服务注册元数据中配置 Config Server 的一些其他属性,以便 Client 端可以正确连接。 如果 Config Server 使用 HTTP Basic 进行保护,则可以将凭据配置为userpassword. 此外,如果 Config Server 具有上下文路径,则可以设置configPath. 例如,以下 YAML 文件适用于作为 Eureka 客户端的 Config Server:spring-doc.cadn.net.cn

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

使用 Eureka 和 WebClient 的 Discovery First Bootstrap

如果您使用 EurekaDiscoveryClient从 Spring Cloud Netflix 中,也想使用WebClient而不是 Jersey 或RestTemplate, 您需要包括WebClient在你的 Classpath 上以及 seteureka.client.webclient.enabled=true.spring-doc.cadn.net.cn

Config 客户端快速失败

在某些情况下,如果服务无法连接到 Config Server,您可能希望服务启动失败。 如果这是所需的行为,请设置 bootstrap 配置属性spring.cloud.config.fail-fast=true使客户端停止并显示 Exception。spring-doc.cadn.net.cn

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

Config 客户端重试

如果您预计 config server 在应用程序启动时可能偶尔不可用,则可以使其在失败后继续尝试。 首先,您需要设置spring.cloud.config.fail-fast=true. 然后你需要添加spring-retryspring-boot-starter-aop添加到您的 Classpath 中。 默认行为是重试六次,初始回退间隔为 1000 毫秒,后续回退的指数乘数为 1.1。 您可以通过设置spring.cloud.config.retry.*configuration 属性。spring-doc.cadn.net.cn

要完全控制重试行为并使用旧版引导程序,请添加@Bean的类型RetryOperationsInterceptor的 ID 为configServerRetryInterceptor. Spring Retry 有一个RetryInterceptorBuilder支持创建一个。

使用 spring.config.import 配置客户端重试

重试适用于 Spring Bootspring.config.import语句和常规属性有效。但是,如果 import 语句位于配置文件中,例如application-prod.properties,则需要另一种方式来配置 retry。配置需要作为 url 参数放在 import 语句上。spring-doc.cadn.net.cn

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.*configuration 属性。spring-doc.cadn.net.cn

查找远程配置资源

Config Service 提供来自以下来源的属性源/{application}/{profile}/{label},其中客户端应用程序中的默认绑定如下所示:spring-doc.cadn.net.cn

在设置属性${spring.application.name}不要在应用名称前加上保留字application-以防止在解析正确的属性源时出现问题。

您可以通过设置spring.cloud.config.*(其中 is*name,profilelabel). 这label对于回滚到以前版本的 Configuration 非常有用。 使用默认的 Config Server 实现,它可以是 git 标签、分支名称或提交 ID。 Label 也可以作为逗号分隔的列表提供。 在这种情况下,将逐个尝试列表中的项目,直到一个项目成功。 在功能分支上工作时,此行为可能很有用。 例如,您可能希望将 config 标签与分支对齐,但将其设置为可选(在这种情况下,使用spring.cloud.config.label=myfeature,develop).spring-doc.cadn.net.cn

为 Config Server 指定多个 URL

为了确保在部署了多个 Config Server 实例并预计一个或多个实例不时不可用时高可用性,您可以指定多个 URL(在spring.cloud.config.uri属性),或者让所有实例在 Service Registry 中注册,如 Eureka (如果使用 Discovery-First Bootstrap 模式)。请注意,这样做仅在 Config Server 未运行时(即应用程序已退出)或发生连接超时时确保高可用性。例如,如果 Config Server 返回 500(内部服务器错误)响应或 Config Client 从 Config Server 收到 401(由于凭据错误或其他原因),则 Config Client 不会尝试从其他 URL 获取属性。此类错误表示用户问题,而不是可用性问题。spring-doc.cadn.net.cn

如果您在 Config Server 上使用 HTTP 基本安全性,则当前只有将凭据嵌入到在spring.cloud.config.uri财产。如果您使用任何其他类型的安全机制,则(当前)无法支持每个 Config Server 的身份验证和授权。spring-doc.cadn.net.cn

配置超时

如果要配置超时阈值:spring-doc.cadn.net.cn

安全

如果您在服务器上使用 HTTP Basic 安全性,则 Client 端需要知道密码(如果不是默认密码,则需要知道用户名)。 您可以通过配置服务器 URI 或通过单独的用户名和密码属性指定用户名和密码,如以下示例所示:spring-doc.cadn.net.cn

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

以下示例显示了传递相同信息的另一种方法:spring-doc.cadn.net.cn

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

spring.cloud.config.passwordspring.cloud.config.username值将覆盖 URI 中提供的任何内容。spring-doc.cadn.net.cn

如果您在 Cloud Foundry 上部署应用程序,则提供密码的最佳方式是通过服务凭证(例如在 URI 中,因为它不需要位于配置文件中)。 以下示例在本地工作,并适用于名为configserver:spring-doc.cadn.net.cn

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

如果配置服务器需要客户端 TLS 证书,则可以通过属性配置客户端 TLS 证书和信任存储,如以下示例所示:spring-doc.cadn.net.cn

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。如果省略 password 属性,则假定 password 为空。spring-doc.cadn.net.cn

如果您使用其他形式的安全性,则可能需要提供RestTemplateConfigServicePropertySourceLocator(例如,通过在 Bootstrap 上下文中获取它并注入它)。spring-doc.cadn.net.cn

运行状况指示器

Config Client 提供了一个 Spring Boot Health Indicator,该指示器尝试从 Config Server 加载配置。 可以通过设置health.config.enabled=false. 出于性能原因,也会缓存响应。 默认缓存生存时间为 5 分钟。 要更改该值,请将health.config.time-to-live属性(以毫秒为单位)。spring-doc.cadn.net.cn

提供自定义 RestTemplate

在某些情况下,您可能需要自定义从 Client 端向 config server 发出的请求。 通常,这样做涉及传递特殊的Authorization标头对向服务器发出的请求进行身份验证。spring-doc.cadn.net.cn

使用 Config 数据提供自定义 RestTemplate

提供自定义RestTemplate使用 Config Data 时:spring-doc.cadn.net.cn

  1. 创建一个实现BootstrapRegistryInitializerspring-doc.cadn.net.cn

    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-doc.cadn.net.cn

    spring.factories
    org.springframework.boot.BootstrapRegistryInitializer=com.my.config.client.CustomBootstrapRegistryInitializer
使用 Bootstrap 提供自定义 RestTemplate

提供自定义RestTemplate使用 Bootstrap 时:spring-doc.cadn.net.cn

  1. 使用PropertySourceLocator,如以下示例所示:spring-doc.cadn.net.cn

    CustomConfigServiceBootstrapConfiguration.java
    @Configuration
    public class CustomConfigServiceBootstrapConfiguration {
        @Bean
        public ConfigServicePropertySourceLocator configServicePropertySourceLocator() {
            ConfigClientProperties clientProperties = configClientProperties();
           ConfigServicePropertySourceLocator configServicePropertySourceLocator =  new ConfigServicePropertySourceLocator(clientProperties);
            configServicePropertySourceLocator.setRestTemplate(customRestTemplate(clientProperties));
            return configServicePropertySourceLocator;
        }
    }
    
    有关添加Authorizationheaders、spring.cloud.config.headers.*属性。
  2. resources/META-INF,创建一个名为spring.factories并指定您的自定义配置,如以下示例所示:spring-doc.cadn.net.cn

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

当使用 Vault 作为配置服务器的后端时,客户端需要为服务器提供一个令牌以从 Vault 中检索值。 此令牌可以在客户端内通过设置spring.cloud.config.tokenbootstrap.yml,如以下示例所示:spring-doc.cadn.net.cn

spring:
  cloud:
    config:
      token: YourVaultToken

Vault 中的嵌套密钥

Vault 支持将键嵌套在 Vault 中存储的值中,如以下示例所示:spring-doc.cadn.net.cn

echo -n '{"appA": {"secret": "appAsecret"}, "bar": "baz"}' | vault write secret/myapp -spring-doc.cadn.net.cn

此命令将 JSON 对象写入您的 Vault。 要在 Spring 中访问这些值,您可以使用传统的点(.) 注释,如以下示例所示spring-doc.cadn.net.cn

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

前面的代码将设置name变量设置为appAsecret.spring-doc.cadn.net.cn