4.0.5

Spring Cloud Config 为分布式系统中的外部化配置提供了服务器端和客户端支持。通过 Config Server,您可以集中管理跨所有环境的应用程序的外部属性。客户端和服务器端的概念与 Spring 的 EnvironmentPropertySource 抽象完全对应,因此它们非常适合 Spring 应用程序,但也可用于任何语言编写的任何应用程序。随着应用程序从开发环境、测试环境迁移到生产环境,您可以管理这些环境之间的配置,并确保应用程序在迁移时拥有运行所需的一切。服务器存储后端的默认实现使用 git,因此它很容易支持带标签的配置环境版本,并且可以通过各种工具访问来管理内容。添加替代实现并将其与 Spring 配置集成也非常容易。

快速入门

本快速入门将指导您使用 Spring Cloud Config Server 的服务器端和客户端。

首先,启动服务器,如下所示

$ cd spring-cloud-config-server
$ ../mvnw spring-boot:run

服务器是一个 Spring Boot 应用程序,因此如果您愿意,可以从您的 IDE 运行它(主类是 ConfigServerApplication)。

接下来尝试客户端,如下所示

$ curl localhost:8888/foo/development
{
  "name": "foo",
  "profiles": [
    "development"
  ]
  ....
  "propertySources": [
    {
      "name": "https://github.com/spring-cloud-samples/config-repo/foo-development.properties",
      "source": {
        "bar": "spam",
        "foo": "from foo development"
      }
    },
    {
      "name": "https://github.com/spring-cloud-samples/config-repo/foo.properties",
      "source": {
        "foo": "from foo props",
        "democonfigclient.message": "hello spring io"
      }
    },
    ....

定位属性源的默认策略是克隆一个 git 仓库(位于 spring.cloud.config.server.git.uri)并用它来初始化一个迷你 SpringApplication。这个迷你应用程序的 Environment 用于枚举属性源并在 JSON 端点发布它们。

HTTP 服务具有以下形式的资源

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

例如

curl localhost:8888/foo/development
curl localhost:8888/foo/development/master
curl localhost:8888/foo/development,db/master
curl localhost:8888/foo-development.yml
curl localhost:8888/foo-db.properties
curl localhost:8888/master/foo-db.properties

其中 applicationSpringApplication 中作为 spring.config.name 注入(在常规 Spring Boot 应用中通常是 application),profile 是活动配置文件(或逗号分隔的属性列表),label 是可选的 git 标签(默认为 master)。

Spring Cloud Config Server 从各种来源为远程客户端拉取配置。以下示例从一个 git 仓库(必须提供)获取配置,如下所示

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo

其他来源包括任何兼容 JDBC 的数据库、Subversion、Hashicorp Vault、Credhub 和本地文件系统。

客户端使用

要在应用程序中使用这些功能,您可以将其构建为一个依赖于 spring-cloud-config-client 的 Spring Boot 应用程序(例如,参见 config-client 的测试用例或示例应用程序)。添加依赖项最方便的方法是使用 Spring Boot 启动器 org.springframework.cloud:spring-cloud-starter-config。Maven 用户还有一个父 pom 和 BOM(spring-cloud-starter-parent),Gradle 和 Spring CLI 用户还有一个 Spring IO 版本管理属性文件。以下示例显示了一个典型的 Maven 配置

pom.xml
   <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>{spring-boot-docs-version}</version>
       <relativePath /> <!-- lookup parent from repository -->
   </parent>

<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-dependencies</artifactId>
			<version>{spring-cloud-version}</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>

<dependencies>
	<dependency>
		<groupId>org.springframework.cloud</groupId>
		<artifactId>spring-cloud-starter-config</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>
</dependencies>

<build>
	<plugins>
           <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
           </plugin>
	</plugins>
</build>

   <!-- repositories also needed for snapshots and milestones -->

现在您可以创建一个标准的 Spring Boot 应用程序,例如以下 HTTP 服务器

@SpringBootApplication
@RestController
public class Application {

    @RequestMapping("/")
    public String home() {
        return "Hello World!";
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

当这个 HTTP 服务器运行时,它会从默认的本地配置服务器(如果正在运行)在 8888 端口获取外部配置。要修改启动行为,您可以通过使用 application.properties 来更改配置服务器的位置,如下所示

spring.config.import=optional:configserver:http://myconfigserver.com

默认情况下,如果没有设置应用程序名称,将使用 application。要修改名称,可以将以下属性添加到 application.properties 文件中

spring.application.name: myapp
设置属性 `${spring.application.name}` 时,不要在您的应用程序名称前面加上保留字 `application-`,以免出现无法解析正确属性源的问题。

Config Server 属性会作为高优先级属性源出现在 `/env` 端点中,如下所示。

$ curl localhost:8080/env
{
  "activeProfiles": [],
  {
    "name": "servletContextInitParams",
    "properties": {}
  },
  {
    "name": "configserver:https://github.com/spring-cloud-samples/config-repo/foo.properties",
    "properties": {
      "foo": {
        "value": "bar",
        "origin": "Config Server https://github.com/spring-cloud-samples/config-repo/foo.properties:2:12"
      }
    }
  },
  ...
}

名为 `configserver:<远程仓库 URL>/<文件名>` 的属性源包含值为 `bar` 的 `foo` 属性。

属性源名称中的 URL 是 git 仓库,而不是配置服务器 URL。
如果您使用 Spring Cloud Config Client,需要设置 `spring.config.import` 属性才能绑定到 Config Server。您可以在Spring Cloud Config 参考指南中阅读更多相关内容。

Spring Cloud Config Server

Spring Cloud Config Server 提供了一个基于 HTTP 资源的 API,用于外部配置(名称-值对或等效的 YAML 内容)。通过使用 `@EnableConfigServer` 注解,该服务器可以嵌入到 Spring Boot 应用程序中。因此,以下应用程序是一个配置服务器

ConfigServer.java
@SpringBootApplication
@EnableConfigServer
public class ConfigServer {
  public static void main(String[] args) {
    SpringApplication.run(ConfigServer.class, args);
  }
}

与所有 Spring Boot 应用程序一样,它默认在 8080 端口运行,但您可以通过各种方式将其切换到更常用的 8888 端口。最简单的方法(也设置了默认配置仓库)是使用 `spring.config.name=configserver` 启动它(Config Server jar 中有一个 `configserver.yml`)。另一种方法是使用您自己的 `application.properties`,如下所示

application.properties
server.port: 8888
spring.cloud.config.server.git.uri: file://${user.home}/config-repo

其中 `${user.home}/config-repo` 是一个包含 YAML 和 properties 文件的 git 仓库。

在 Windows 上,如果文件 URL 是带有驱动器前缀的绝对路径,则需要额外添加一个 "/"(例如,`file:///${user.home}/config-repo`)。

以下列表显示了在前面的示例中创建 git 仓库的方法

$ cd $HOME
$ mkdir config-repo
$ cd config-repo
$ git init .
$ echo info.foo: bar > application.properties
$ git add -A .
$ git commit -m "Add application.properties"
将本地文件系统用于您的 git 仓库仅用于测试目的。在生产环境中,您应该使用服务器来托管您的配置仓库。
如果您的配置仓库中只保留文本文件,则首次克隆会快速高效。如果存储二进制文件,特别是大型文件,在首次请求配置时可能会遇到延迟,或在服务器中遇到内存不足错误。

环境仓库

您应该在哪里存储 Config Server 的配置数据?管理此行为的策略是 `EnvironmentRepository`,它提供 `Environment` 对象。此 `Environment` 是 Spring `Environment` 领域的浅拷贝(主要特征是包含 `propertySources`)。`Environment` 资源由三个变量参数化

  • {application},在客户端映射到 spring.application.name

  • {profile},在客户端映射到 spring.profiles.active(逗号分隔列表)。

  • {label},这是一个服务器端功能,用于标记一组“版本化”的配置文件。

仓库实现通常表现得像一个 Spring Boot 应用程序,从与 {application} 参数相等的 `spring.config.name` 和与 {profiles} 参数相等的 `spring.profiles.active` 中加载配置文件。配置文件的优先级规则与常规 Spring Boot 应用程序中相同:活动配置文件优先于默认配置,如果存在多个配置文件,则最后一个配置文件获胜(类似于向 `Map` 中添加条目)。

以下示例客户端应用程序具有此引导配置

spring:
  application:
    name: foo
  profiles:
    active: dev,mysql

(与常规 Spring Boot 应用程序一样,这些属性也可以通过环境变量或命令行参数设置)。

如果仓库是基于文件的,服务器会从 `application.yml`(所有客户端共享)和 `foo.yml`(`foo.yml` 优先)创建一个 `Environment`。如果 YAML 文件内部有指向 Spring 配置文件的文档,则这些配置文件的优先级更高(按列出的配置文件顺序)。如果存在特定于配置文件的 YAML(或 properties)文件,这些文件的优先级也高于默认文件。更高的优先级意味着在 `Environment` 中更早列出的 `PropertySource`。(这些相同的规则也适用于独立的 Spring Boot 应用程序)。

您可以将 `spring.cloud.config.server.accept-empty` 设置为 `false`,以便在找不到应用程序时服务器返回 HTTP 404 状态。默认情况下,此标志设置为 `true`。

您不能将 `spring.main.*` 属性放在远程 `EnvironmentRepository` 中。这些属性用作应用程序初始化的一部分。

Git 后端

EnvironmentRepository 的默认实现使用 Git 后端,这对于管理升级、物理环境和审计更改非常方便。要更改仓库位置,可以在 Config Server 中设置 `spring.cloud.config.server.git.uri` 配置属性(例如在 `application.yml` 中)。如果使用 `file:` 前缀设置它,则应从本地仓库工作,以便您可以快速轻松地开始,而无需服务器。但是,在这种情况下,服务器直接在本地仓库上操作,而无需克隆它(即使它不是裸仓库也没关系,因为 Config Server 从不更改“远程”仓库)。要扩展 Config Server 并使其高可用,您需要将服务器的所有实例指向同一个仓库,因此只有共享文件系统才能工作。即使在这种情况下,对于共享文件系统仓库,最好使用 `ssh:` 协议,以便服务器可以克隆它并使用本地工作副本作为缓存。

此仓库实现将 HTTP 资源的 {label} 参数映射到 git 标签(提交 ID、分支名称或标签)。如果 git 分支或标签名称包含斜杠(/),则 HTTP URL 中的标签应改用特殊字符串 (_) 指定(以避免与其他 URL 路径产生歧义)。例如,如果标签是 foo/bar,替换斜杠后将得到以下标签:foo(_)bar。特殊字符串 (_) 的包含也可以应用于 {application} 参数。如果您使用诸如 curl 之类的命令行客户端,请注意 URL 中的括号 - 您应该用单引号 ('') 从 shell 中转义它们。

跳过 SSL 证书验证

通过将 `git.skipSslValidation` 属性设置为 `true`(默认为 `false`),可以禁用配置服务器对 Git 服务器 SSL 证书的验证。

spring:
  cloud:
    config:
      server:
        git:
          uri: https://example.com/my/repo
          skipSslValidation: true
设置 HTTP 连接超时

您可以配置配置服务器等待获取 HTTP 连接的时间(以秒为单位)。使用 `git.timeout` 属性(默认为 `5`)。

spring:
  cloud:
    config:
      server:
        git:
          uri: https://example.com/my/repo
          timeout: 4
Git URI 中的占位符

Spring Cloud Config Server 支持在 git 仓库 URL 中使用 {application}{profile} 的占位符(如果需要也可以使用 {label},但请记住标签无论如何都会作为 git 标签应用)。因此,您可以使用类似于以下的结构来支持“每个应用程序一个仓库”的策略

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/myorg/{application}

您也可以使用类似的模式,但使用 {profile} 来支持“每个配置文件一个仓库”的策略。

此外,在您的 {application} 参数中使用特殊字符串 "(_)" 可以支持多个组织,如下例所示

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/{application}

其中 {application} 在请求时以以下格式提供:organization(_)application

模式匹配和多个仓库

Spring Cloud Config 还支持更复杂的要求,可以在应用程序和配置文件名称上进行模式匹配。模式格式是逗号分隔的 {application}/{profile} 名称列表,带有通配符(注意以通配符开头的模式可能需要引用),如下例所示

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          repos:
            simple: https://github.com/simple/config-repo
            special:
              pattern: special*/dev*,*special*/dev*
              uri: https://github.com/special/config-repo
            local:
              pattern: local*
              uri: file:/home/configsvc/config-repo

如果 {application}/{profile} 与任何模式都不匹配,则使用 spring.cloud.config.server.git.uri 下定义的默认 URI。在上面的示例中,对于“simple”仓库,模式是 simple/*(它只匹配所有配置文件中名为 simple 的一个应用程序)。“local”仓库匹配所有配置文件中以 local 开头的所有应用程序名称(/* 后缀会自动添加到任何没有配置文件匹配器的模式中)。

“simple”示例中使用的“单行”快捷方式仅在需要设置的唯一属性是 URI 时使用。如果您需要设置其他任何内容(凭据、模式等),则需要使用完整形式。

仓库中的 `pattern` 属性实际上是一个数组,因此您可以使用 YAML 数组(或 properties 文件中的 [0][1] 等后缀)绑定到多个模式。如果您要运行具有多个配置文件的应用程序,可能需要这样做,如下例所示

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          repos:
            development:
              pattern:
                - '*/development'
                - '*/staging'
              uri: https://github.com/development/config-repo
            staging:
              pattern:
                - '*/qa'
                - '*/production'
              uri: https://github.com/staging/config-repo
Spring Cloud 会猜测,如果模式中包含的配置文件不以 * 结尾,则表示您实际上希望匹配以该模式开头的一系列配置文件(因此 */staging["*/staging", "*/staging,*"] 等的快捷方式)。这在需要例如在本地运行“开发”配置文件中的应用程序,同时在远程运行“云”配置文件中的应用程序时很常见。

每个仓库还可以选择将配置文件存储在子目录中,并且可以指定搜索这些目录的模式作为 search-paths。以下示例显示了顶级目录中的配置文件

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          search-paths:
            - foo
            - bar*

在上面的示例中,服务器在顶级目录和 foo/ 子目录中搜索配置文件,同时也在任何名称以 bar 开头的子目录中搜索。

默认情况下,服务器在首次请求配置时克隆远程仓库。服务器可以配置为在启动时克隆仓库,如下面的顶级示例所示

spring:
  cloud:
    config:
      server:
        git:
          uri: https://git/common/config-repo.git
          repos:
            team-a:
                pattern: team-a-*
                cloneOnStart: true
                uri: https://git/team-a/config-repo.git
            team-b:
                pattern: team-b-*
                cloneOnStart: false
                uri: https://git/team-b/config-repo.git
            team-c:
                pattern: team-c-*
                uri: https://git/team-a/config-repo.git

在前面的示例中,服务器在启动时克隆 team-a 的 config-repo,然后才接受任何请求。所有其他仓库直到从该仓库请求配置时才会被克隆。

在 Config Server 启动时设置要克隆的仓库有助于在 Config Server 启动过程中快速识别配置错误的配置源(例如无效的仓库 URI)。如果没有为配置源启用 cloneOnStart,则 Config Server 可能会成功启动,即使配置源配置错误或无效,直到应用程序从该配置源请求配置时才检测到错误。
认证

要在远程仓库上使用 HTTP 基本认证,请单独添加 usernamepassword 属性(不要在 URL 中),如下例所示

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          username: trolley
          password: strongpassword

如果您不使用 HTTPS 和用户凭据,当您将密钥存储在默认目录(~/.ssh)中且 URI 指向 SSH 位置(例如 `[email protected]:configuration/cloud-configuration`)时,SSH 也应该可以直接工作。重要的是 ~/.ssh/known_hosts 文件中必须包含 Git 服务器的条目,并且格式为 ssh-rsa。不支持其他格式(例如 ecdsa-sha2-nistp256)。为避免意外,您应确保 known_hosts 文件中仅包含 Git 服务器的一个条目,并且该条目与您提供给配置服务器的 URL 匹配。如果您在 URL 中使用主机名,则希望 known_hosts 文件中也使用完全相同的主机名(而不是 IP)。仓库通过 JGit 访问,因此您能找到的任何关于 JGit 的文档都应该适用。HTTPS 代理设置可以在 ~/.git/config 中设置,或者(与任何其他 JVM 进程相同的方式)通过系统属性(-Dhttps.proxyHost-Dhttps.proxyPort)设置。

如果您不知道您的 ~/.git 目录在哪里,请使用 git config --global 来操作设置(例如,git config --global http.sslVerify false)。

JGit 需要 PEM 格式的 RSA 密钥。下面是一个 ssh-keygen(来自 openssh)命令的示例,它将生成正确格式的密钥

ssh-keygen -m PEM -t rsa -b 4096 -f ~/config_server_deploy_key.rsa

警告:使用 SSH 密钥时,预期的 SSH 私钥必须以 -----BEGIN RSA PRIVATE KEY----- 开头。如果密钥以 -----BEGIN OPENSSH PRIVATE KEY----- 开头,则在 Spring Cloud Config Server 启动时将无法加载 RSA 密钥。错误看起来像

- Error in object 'spring.cloud.config.server.git': codes [PrivateKeyIsValid.spring.cloud.config.server.git,PrivateKeyIsValid]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [spring.cloud.config.server.git.,]; arguments []; default message []]; default message [Property 'spring.cloud.config.server.git.privateKey' is not a valid private key]

要纠正上述错误,RSA 密钥必须转换为 PEM 格式。上面提供了一个使用 openssh 生成相应格式的新密钥的示例。

使用 AWS CodeCommit 认证

Spring Cloud Config Server 也支持 AWS CodeCommit 认证。AWS CodeCommit 在命令行使用 Git 时使用一个认证助手。JGit 库不使用此助手,因此如果 Git URI 匹配 AWS CodeCommit 模式,则会创建一个 AWS CodeCommit 的 JGit CredentialProvider。AWS CodeCommit URI 遵循以下模式

https://git-codecommit.${AWS_REGION}.amazonaws.com/v1/repos/${repo}

如果您随 AWS CodeCommit URI 提供用户名和密码,它们必须是提供仓库访问权限的 AWS accessKeyId 和 secretAccessKey。如果您未指定用户名和密码,则会使用 Default Credential Provider Chain 获取 accessKeyId 和 secretAccessKey。

如果您的 Git URI 匹配 CodeCommit URI 模式(如前所示),则必须在用户名和密码中提供有效的 AWS 凭据,或在默认凭据提供者链支持的任一位置提供凭据。AWS EC2 实例可以使用 EC2 实例的 IAM 角色

software.amazon.awssdk:auth jar 是一个可选依赖项。如果类路径中没有 software.amazon.awssdk:auth jar,则无论 git 服务器 URI 如何,都不会创建 AWS Code Commit 凭据提供者。
使用 Google Cloud Source 认证

Spring Cloud Config Server 也支持针对 Google Cloud Source 仓库进行认证。

如果您的 Git URI 使用 httphttps 协议,并且域名是 source.developers.google.com,则将使用 Google Cloud Source 凭据提供者。Google Cloud Source 仓库 URI 的格式为 https://source.developers.google.com/p/${GCP_PROJECT}/r/${REPO}。要获取仓库的 URI,请在 Google Cloud Source UI 中点击“克隆”,然后选择“手动生成凭据”。不要生成任何凭据,只需复制显示的 URI。

Google Cloud Source 凭据提供者将使用 Google Cloud Platform 应用程序默认凭据。有关如何为系统创建应用程序默认凭据的信息,请参阅Google Cloud SDK 文档。此方法适用于开发环境中的用户账户和生产环境中的服务账户。

com.google.auth:google-auth-library-oauth2-http 是一个可选依赖项。如果类路径中没有 google-auth-library-oauth2-http jar,则无论 git 服务器 URI 如何,都不会创建 Google Cloud Source 凭据提供者。
Git SSH 配置使用属性

默认情况下,Spring Cloud Config Server 使用的 JGit 库在使用 SSH URI 连接到 Git 仓库时,会使用 SSH 配置文件,例如 ~/.ssh/known_hosts/etc/ssh/ssh_config。在 Cloud Foundry 等云环境中,本地文件系统可能是临时的或不易访问。对于这些情况,可以使用 Java 属性设置 SSH 配置。为了激活基于属性的 SSH 配置,必须将 spring.cloud.config.server.git.ignoreLocalSshSettings 属性设置为 true,如下例所示

  spring:
    cloud:
      config:
        server:
          git:
            uri: [email protected]:team/repo1.git
            ignoreLocalSshSettings: true
            hostKey: someHostKey
            hostKeyAlgorithm: ssh-rsa
            privateKey: |
                         -----BEGIN RSA PRIVATE KEY-----
                         MIIEpgIBAAKCAQEAx4UbaDzY5xjW6hc9jwN0mX33XpTDVW9WqHp5AKaRbtAC3DqX
                         IXFMPgw3K45jxRb93f8tv9vL3rD9CUG1Gv4FM+o7ds7FRES5RTjv2RT/JVNJCoqF
                         ol8+ngLqRZCyBtQN7zYByWMRirPGoDUqdPYrj2yq+ObBBNhg5N+hOwKjjpzdj2Ud
                         1l7R+wxIqmJo1IYyy16xS8WsjyQuyC0lL456qkd5BDZ0Ag8j2X9H9D5220Ln7s9i
                         oezTipXipS7p7Jekf3Ywx6abJwOmB0rX79dV4qiNcGgzATnG1PkXxqt76VhcGa0W
                         DDVHEEYGbSQ6hIGSh0I7BQun0aLRZojfE3gqHQIDAQABAoIBAQCZmGrk8BK6tXCd
                         fY6yTiKxFzwb38IQP0ojIUWNrq0+9Xt+NsypviLHkXfXXCKKU4zUHeIGVRq5MN9b
                         BO56/RrcQHHOoJdUWuOV2qMqJvPUtC0CpGkD+valhfD75MxoXU7s3FK7yjxy3rsG
                         EmfA6tHV8/4a5umo5TqSd2YTm5B19AhRqiuUVI1wTB41DjULUGiMYrnYrhzQlVvj
                         5MjnKTlYu3V8PoYDfv1GmxPPh6vlpafXEeEYN8VB97e5x3DGHjZ5UrurAmTLTdO8
                         +AahyoKsIY612TkkQthJlt7FJAwnCGMgY6podzzvzICLFmmTXYiZ/28I4BX/mOSe
                         pZVnfRixAoGBAO6Uiwt40/PKs53mCEWngslSCsh9oGAaLTf/XdvMns5VmuyyAyKG
                         ti8Ol5wqBMi4GIUzjbgUvSUt+IowIrG3f5tN85wpjQ1UGVcpTnl5Qo9xaS1PFScQ
                         xrtWZ9eNj2TsIAMp/svJsyGG3OibxfnuAIpSXNQiJPwRlW3irzpGgVx/AoGBANYW
                         dnhshUcEHMJi3aXwR12OTDnaLoanVGLwLnkqLSYUZA7ZegpKq90UAuBdcEfgdpyi
                         PhKpeaeIiAaNnFo8m9aoTKr+7I6/uMTlwrVnfrsVTZv3orxjwQV20YIBCVRKD1uX
                         VhE0ozPZxwwKSPAFocpyWpGHGreGF1AIYBE9UBtjAoGBAI8bfPgJpyFyMiGBjO6z
                         FwlJc/xlFqDusrcHL7abW5qq0L4v3R+FrJw3ZYufzLTVcKfdj6GelwJJO+8wBm+R
                         gTKYJItEhT48duLIfTDyIpHGVm9+I1MGhh5zKuCqIhxIYr9jHloBB7kRm0rPvYY4
                         VAykcNgyDvtAVODP+4m6JvhjAoGBALbtTqErKN47V0+JJpapLnF0KxGrqeGIjIRV
                         cYA6V4WYGr7NeIfesecfOC356PyhgPfpcVyEztwlvwTKb3RzIT1TZN8fH4YBr6Ee
                         KTbTjefRFhVUjQqnucAvfGi29f+9oE3Ei9f7wA+H35ocF6JvTYUsHNMIO/3gZ38N
                         CPjyCMa9AoGBAMhsITNe3QcbsXAbdUR00dDsIFVROzyFJ2m40i4KCRM35bC/BIBs
                         q0TY3we+ERB40U8Z2BvU61QuwaunJ2+uGadHo58VSVdggqAo0BSkH58innKKt96J
                         69pcVH/4rmLbXdcmNYGm6iu+MlPQk4BUZknHSmVHIFdJ0EPupVaQ8RHT
                         -----END RSA PRIVATE KEY-----

下表描述了 SSH 配置属性。

表 1. SSH 配置属性
属性名称 备注

ignoreLocalSshSettings

如果为 true,则使用基于属性而不是基于文件的 SSH 配置。必须设置为 spring.cloud.config.server.git.ignoreLocalSshSettings不能在仓库定义内部设置。

privateKey

有效的 SSH 私钥。如果 ignoreLocalSshSettings 为 true 且 Git URI 为 SSH 格式,则必须设置此属性。

hostKey

有效的 SSH 主机密钥。如果 hostKeyAlgorithm 也已设置,则必须设置此属性。

hostKeyAlgorithm

以下之一:ssh-dss, ssh-rsa, ssh-ed25519, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384, or ecdsa-sha2-nistp521。如果 hostKey 也已设置,则必须设置此属性。

strictHostKeyChecking

truefalse。如果为 false,则忽略主机密钥错误。

knownHostsFile

自定义 .known_hosts 文件的位置。

preferredAuthentications

覆盖服务器认证方法顺序。如果服务器在 publickey 方法之前具有键盘交互式认证,这应该可以避免登录提示。

Git 搜索路径中的占位符

Spring Cloud Config Server 也支持带有 {application}{profile} 占位符(以及 {label},如果需要)的搜索路径,如下例所示

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          search-paths: '{application}'

前面的列表导致在仓库中搜索与目录同名的文件(以及顶级目录中的文件)。带有占位符的搜索路径中也支持通配符(任何匹配的目录都包含在搜索中)。

在 Git 仓库中强制拉取

如前所述,如果本地副本变得“脏”(例如,文件夹内容因操作系统进程而改变),导致 Spring Cloud Config Server 无法从远程仓库更新本地副本,它会克隆远程 git 仓库。

为了解决这个问题,有一个 force-pull 属性,它可以使 Spring Cloud Config Server 在本地副本“脏”时强制从远程仓库拉取,如下例所示

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          force-pull: true

如果您有多个仓库配置,可以为每个仓库配置 force-pull 属性,如下例所示

spring:
  cloud:
    config:
      server:
        git:
          uri: https://git/common/config-repo.git
          force-pull: true
          repos:
            team-a:
                pattern: team-a-*
                uri: https://git/team-a/config-repo.git
                force-pull: true
            team-b:
                pattern: team-b-*
                uri: https://git/team-b/config-repo.git
                force-pull: true
            team-c:
                pattern: team-c-*
                uri: https://git/team-a/config-repo.git
force-pull 属性的默认值是 false
删除 Git 仓库中未跟踪的分支

由于 Spring Cloud Config Server 在将分支检出到本地仓库(例如按标签获取属性)后会保留远程 git 仓库的克隆,它会一直保留该分支,直到下次服务器重启(这将创建新的本地仓库)。因此,可能会出现远程分支已被删除,但其本地副本仍然可用于获取的情况。如果 Spring Cloud Config Server 客户端服务以 --spring.cloud.config.label=deletedRemoteBranch,master 启动,它将从 deletedRemoteBranch 本地分支获取属性,而不是从 master 获取。

为了保持本地仓库分支干净并与远程同步,可以设置 deleteUntrackedBranches 属性。它将使 Spring Cloud Config Server 强制删除本地仓库中未跟踪的分支。示例

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          deleteUntrackedBranches: true
deleteUntrackedBranches 属性的默认值是 false
Git 刷新率

您可以使用 spring.cloud.config.server.git.refreshRate 控制配置服务器从 Git 后端获取更新配置数据的频率。此属性的值以秒为单位指定。默认值为 0,表示配置服务器在每次请求时都会从 Git 仓库获取更新的配置。

默认标签

Git 使用的默认标签是 main。如果您未设置 spring.cloud.config.server.git.defaultLabel 且不存在名为 main 的分支,配置服务器默认也会尝试检出名为 master 的分支。如果您想禁用回退分支行为,可以将 spring.cloud.config.server.git.tryMasterBranch 设置为 false

版本控制后端文件系统使用

对于基于 VCS 的后端(git, svn),文件会被检出或克隆到本地文件系统。默认情况下,它们会存放在系统临时目录中,前缀为 config-repo-。例如在 Linux 上,可能是 /tmp/config-repo-<randomid>。某些操作系统会定期清理临时目录。这可能导致意外行为,例如属性丢失。为避免此问题,请通过设置 spring.cloud.config.server.git.basedirspring.cloud.config.server.svn.basedir 将 Config Server 使用的目录更改为不在系统临时目录结构中的目录。

文件系统后端

Config Server 中还有一个“native”配置文件,它不使用 Git,而是从本地类路径或文件系统加载配置文件(可以使用 spring.cloud.config.server.native.searchLocations 指向任何静态 URL)。要使用 native 配置文件,请使用 spring.profiles.active=native 启动 Config Server。

请记住为文件资源使用 file: 前缀(没有前缀时默认通常是类路径)。与任何 Spring Boot 配置一样,您可以嵌入 ${} 风格的环境占位符,但请记住 Windows 中的绝对路径需要额外加一个 /(例如,file:///${user.home}/config-repo)。
searchLocations 的默认值与本地 Spring Boot 应用程序相同(即 [classpath:/, classpath:/config, file:./, file:./config])。这不会将服务器中的 application.properties 公开给所有客户端,因为服务器中存在的任何属性源在发送给客户端之前都会被移除。
文件系统后端对于快速上手和测试非常有用。要在生产环境中使用它,需要确保文件系统可靠并且在 Config Server 的所有实例之间共享。

搜索位置可以包含 {application}{profile}{label} 的占位符。通过这种方式,您可以在路径中隔离目录,并选择对您有意义的策略(例如,每个应用程序一个子目录或每个配置文件一个子目录)。

如果您在搜索位置中不使用占位符,此仓库还会将 HTTP 资源的 {label} 参数附加到搜索路径的后缀上,因此属性文件会从每个搜索位置以及与标签同名的子目录中加载(带标签的属性在 Spring Environment 中具有更高优先级)。因此,没有占位符时的默认行为与添加以 /{label}/ 结尾的搜索位置相同。例如,file:/tmp/configfile:/tmp/config,file:/tmp/config/{label} 相同。可以通过设置 spring.cloud.config.server.native.addLabelLocations=false 来禁用此行为。

Vault 后端

Spring Cloud Config Server 也支持将 Vault 作为后端。

Vault 是一个用于安全访问秘密的工具。秘密是指您希望严格控制访问的任何内容,例如 API 密钥、密码、证书和其他敏感信息。Vault 为任何秘密提供统一接口,同时提供严格的访问控制并记录详细的审计日志。

有关 Vault 的更多信息,请参阅Vault 快速入门指南

要使配置服务器使用 Vault 后端,您可以使用 vault 配置文件运行您的配置服务器。例如,在配置服务器的 application.properties 中,可以添加 spring.profiles.active=vault

默认情况下,Spring Cloud Config Server 使用基于 Token 的认证从 Vault 获取配置。Vault 还支持其他认证方法,如 AppRole、LDAP、JWT、CloudFoundry、Kubernetes Auth。为了使用除 TOKEN 或 X-Config-Token 头之外的任何认证方法,我们需要在类路径中包含 Spring Vault Core,以便 Config Server 可以将认证委托给该库。请将以下依赖项添加到您的 Config Server App 中。

Maven (pom.xml)

<dependencies>
	<dependency>
		<groupId>org.springframework.vault</groupId>
		<artifactId>spring-vault-core</artifactId>
	</dependency>
</dependencies>

Gradle (build.gradle)

dependencies {
    implementation "org.springframework.vault:spring-vault-core"
}

默认情况下,配置服务器假定您的 Vault 服务器运行在 http://127.0.0.1:8200。它还假定后端名称是 secret,密钥是 application。所有这些默认值都可以在您的配置服务器的 application.properties 中配置。下表描述了可配置的 Vault 属性

名称 默认值

host

127.0.0.1

port

8200

scheme

http

backend

secret

defaultKey

application

profileSeparator

,

kvVersion

1

skipSslValidation

false

timeout

5

namespace

null

前面表格中的所有属性都必须以 spring.cloud.config.server.vault 作为前缀,或者放置在复合配置的正确 Vault 部分中。

所有可配置属性都可以在 org.springframework.cloud.config.server.environment.VaultEnvironmentProperties 中找到。

Vault 0.10.0 引入了版本化的键值后端(k/v 后端版本 2),它与早期版本公开了不同的 API,现在需要在挂载路径和实际上下文路径之间加上 data/,并将秘密信息包装在一个 data 对象中。设置 spring.cloud.config.server.vault.kv-version=2 将考虑这一点。

可选地,支持 Vault Enterprise 的 X-Vault-Namespace 头部。要将其发送到 Vault,请设置 namespace 属性。

Config Server 运行后,您可以向服务器发起 HTTP 请求以从 Vault 后端检索值。为此,您需要 Vault 服务器的令牌。

首先,在 Vault 中放置一些数据,如下例所示:

$ vault kv put secret/application foo=bar baz=bam
$ vault kv put secret/myapp foo=myappsbar

其次,向 Config Server 发起 HTTP 请求以检索值,如下例所示:

$ curl -X "GET" "http://localhost:8888/myapp/default" -H "X-Config-Token: yourtoken"

您应该看到类似以下的响应:

{
   "name":"myapp",
   "profiles":[
      "default"
   ],
   "label":null,
   "version":null,
   "state":null,
   "propertySources":[
      {
         "name":"vault:myapp",
         "source":{
            "foo":"myappsbar"
         }
      },
      {
         "name":"vault:application",
         "source":{
            "baz":"bam",
            "foo":"bar"
         }
      }
   ]
}

客户端向 Config Server 提供与 Vault 通信所需身份验证的默认方式是设置 X-Config-Token 头部。但是,您可以省略该头部,并通过设置与 Spring Cloud Vault 相同的配置属性,在服务器中配置身份验证。要设置的属性是 spring.cloud.config.server.vault.authentication。它应设置为支持的身份验证方法之一。您可能还需要设置特定于您使用的身份验证方法的其他属性,使用与 spring.cloud.vault 文档中相同的属性名称,但前缀更改为 spring.cloud.config.server.vault。有关更多详细信息,请参阅 Spring Cloud Vault 参考指南

如果您省略 X-Config-Token 头部并使用服务器属性设置身份验证,则 Config Server 应用程序需要额外依赖 Spring Vault 才能启用附加的身份验证选项。有关如何添加该依赖项的信息,请参阅 Spring Vault 参考指南
多属性源

使用 Vault 时,您可以为应用程序提供多个属性源。例如,假设您已将数据写入 Vault 中的以下路径:

secret/myApp,dev
secret/myApp
secret/application,dev
secret/application

写入 secret/application 的属性可供所有使用 Config Server 的应用程序使用。名为 myApp 的应用程序可以使用写入 secret/myAppsecret/application 的任何属性。当 myApp 启用 dev profile 时,写入上述所有路径的属性都将对其可用,列表中的第一个路径中的属性优先于其他路径。

通过代理访问后端

配置服务器可以通过 HTTP 或 HTTPS 代理访问 Git 或 Vault 后端。此行为通过 proxy.httpproxy.https 下的设置为 Git 或 Vault 进行控制。这些设置是针对每个仓库的,因此如果您使用的是复合环境仓库,则必须为复合仓库中的每个后端单独配置代理设置。如果您使用的网络需要独立的代理服务器用于 HTTP 和 HTTPS URL,则可以为单个后端配置 HTTP 和 HTTPS 代理设置:在这种情况下,http 访问将使用 http 代理,https 访问将使用 https 代理。此外,您可以使用应用程序和代理之间的代理定义协议指定一个将用于两种协议的单一代理。

下表描述了 HTTP 和 HTTPS 代理的代理配置属性。所有这些属性都必须以 proxy.httpproxy.https 为前缀。

表 2. 代理配置属性
属性名称 备注

host

代理的主机。

port

访问代理的端口。

nonProxyHosts

配置服务器应通过代理外部访问的任何主机。如果为 proxy.http.nonProxyHostsproxy.https.nonProxyHosts 都提供了值,将使用 proxy.http 的值。

username

用于向代理进行身份验证的用户名。如果为 proxy.http.usernameproxy.https.username 都提供了值,将使用 proxy.http 的值。

password

用于向代理进行身份验证的密码。如果为 proxy.http.passwordproxy.https.password 都提供了值,将使用 proxy.http 的值。

以下配置使用 HTTPS 代理访问 Git 仓库。

spring:
  profiles:
    active: git
  cloud:
    config:
      server:
        git:
          uri: https://github.com/spring-cloud-samples/config-repo
          proxy:
            https:
              host: my-proxy.host.io
              password: myproxypassword
              port: '3128'
              username: myproxyusername
              nonProxyHosts: example.com

与所有应用程序共享配置

与所有应用程序共享配置的方法因您采用的方式而异,如下列主题所述:

基于文件的仓库

对于基于文件(git、svn 和 native)的仓库,文件名为 application*application.propertiesapplication.ymlapplication-*.properties 等)的资源会在所有客户端应用程序之间共享。您可以使用这些文件名的资源来配置全局默认值,并根据需要由应用程序特定的文件进行覆盖。

属性覆盖功能也可用于设置全局默认值,并允许应用程序通过占位符在本地覆盖它们。

使用“native” profile(本地文件系统后端)时,您应该使用一个不在服务器自身配置中的显式搜索位置。否则,默认搜索位置中的 application* 资源将被移除,因为它们是服务器的一部分。
Vault 服务器

使用 Vault 作为后端时,您可以通过将配置放置在 secret/application 中来与所有应用程序共享配置。例如,如果您运行以下 Vault 命令,所有使用 Config Server 的应用程序都将拥有 foobaz 属性:

$ vault write secret/application foo=bar baz=bam
CredHub 服务器

使用 CredHub 作为后端时,您可以通过将配置放置在 /application/ 中或将其放置在应用程序的 default profile 中来与所有应用程序共享配置。例如,如果您运行以下 CredHub 命令,所有使用 Config Server 的应用程序都将拥有 shared.color1shared.color2 属性:

credhub set --name "/application/profile/master/shared" --type=json
value: {"shared.color1": "blue", "shared.color": "red"}
credhub set --name "/my-app/default/master/more-shared" --type=json
value: {"shared.word1": "hello", "shared.word2": "world"}

AWS Secrets Manager

使用 AWS Secrets Manager 作为后端时,您可以通过将配置放置在 /application/ 中或将其放置在应用程序的 default profile 中来与所有应用程序共享配置。例如,如果您添加键为以下内容的秘密信息,所有使用 Config Server 的应用程序都将拥有 shared.fooshared.bar 属性:

secret name = /secret/application-default/
secret value =
{
 shared.foo: foo,
 shared.bar: bar
}

secret name = /secret/application/
secret value =
{
 shared.foo: foo,
 shared.bar: bar
}
带标签的版本

AWS Secrets Manager 仓库允许以 Git 后端相同的方式保存带标签的配置环境版本。

仓库实现将 HTTP 资源的 {label} 参数映射到 AWS Secrets Manager 秘密信息的暂存标签。要创建带标签的秘密信息,请创建秘密信息或更新其内容并为其定义一个暂存标签(有时在 AWS 文档中称为版本阶段)。例如:

$ aws secretsmanager create-secret \
      --name /secret/test/ \
      --secret-string '{"version":"1"}'
{
    "ARN": "arn:aws:secretsmanager:us-east-1:123456789012:secret:/secret/test/-a1b2c3",
    "Name": "/secret/test/",
    "VersionId": "cd291674-de2f-41de-8f3b-37dbf4880d69"
}

$ aws secretsmanager update-secret-version-stage \
      --secret-id /secret/test/ \
      --version-stage 1.0.0 \
      --move-to-version-id cd291674-de2f-41de-8f3b-37dbf4880d69

{
    "ARN": "arn:aws:secretsmanager:us-east-1:123456789012:secret:/secret/test/-a1b2c3",
    "Name": "/secret/test/",
}

使用 spring.cloud.config.server.aws-secretsmanager.default-label 属性设置默认标签。如果未定义此属性,后端将使用 AWSCURRENT 作为暂存标签。

spring:
  profiles:
    active: aws-secretsmanager
  cloud:
    config:
      server:
        aws-secretsmanager:
          region: us-east-1
          default-label: 1.0.0

请注意,如果未设置默认标签且请求未定义标签,仓库将像禁用带标签版本支持一样使用秘密信息。此外,默认标签仅在启用带标签支持时使用。否则,定义此属性毫无意义。

请注意,如果暂存标签包含斜杠(/),则 HTTP URL 中的标签应改为用特殊字符串 (_) 指定(以避免与其他 URL 路径产生歧义),其方式与 Git 后端部分所述相同。

使用 spring.cloud.config.server.aws-secretsmanager.ignore-label 属性可以忽略 HTTP 资源的 {label} 参数以及 spring.cloud.config.server.aws-secretsmanager.default-label 属性。仓库将像禁用带标签版本支持一样使用秘密信息。

spring:
  profiles:
    active: aws-secretsmanager
  cloud:
    config:
      server:
        aws-secretsmanager:
          region: us-east-1
          ignore-label: true

AWS Parameter Store

使用 AWS Parameter Store 作为后端时,您可以通过将属性放置在 /application 层次结构中来与所有应用程序共享配置。

例如,如果您添加名称为以下内容的参数,所有使用 Config Server 的应用程序都将拥有 foo.barfred.baz 属性:

/config/application/foo.bar
/config/application-default/fred.baz

JDBC 后端

Spring Cloud Config Server 支持将 JDBC(关系型数据库)作为配置属性的后端。您可以通过向 classpath 添加 spring-boot-starter-data-jdbc 并使用 jdbc profile,或者添加一个类型为 JdbcEnvironmentRepository 的 bean 来启用此功能。如果您在 classpath 中包含正确的依赖项(有关更多详细信息,请参阅用户指南),Spring Boot 会配置一个数据源。

您可以通过将 spring.cloud.config.server.jdbc.enabled 属性设置为 false 来禁用 JdbcEnvironmentRepository 的自动配置。

数据库需要有一个名为 PROPERTIES 的表,包含 APPLICATIONPROFILELABEL 列(具有通常的 Environment 含义),以及用于 Properties 风格的键值对的 KEYVALUE 列。所有字段在 Java 中都是 String 类型,因此您可以根据需要将其设为任意长度的 VARCHAR。属性值的行为方式与来自名为 {application}-{profile}.properties 的 Spring Boot 属性文件中的属性值相同,包括所有加密和解密,这些将作为后处理步骤应用(即,不直接在仓库实现中)。

用于 JDBC 的默认标签是 master。您可以通过设置 spring.cloud.config.server.jdbc.defaultLabel 来更改它。

Redis 后端

Spring Cloud Config Server 支持将 Redis 作为配置属性的后端。您可以通过添加对 Spring Data Redis 的依赖项来启用此功能。

pom.xml
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>
</dependencies>

以下配置使用 Spring Data RedisTemplate 访问 Redis。我们可以使用 spring.redis.* 属性来覆盖默认连接设置。

spring:
  profiles:
    active: redis
  redis:
    host: redis
    port: 16379

属性应作为字段存储在哈希中。哈希的名称应与 spring.application.name 属性相同,或者为 spring.application.namespring.profiles.active[n] 的组合。

HMSET sample-app server.port "8100" sample.topic.name "test" test.property1 "property1"

运行上面可见的命令后,哈希应该包含以下键值对:

HGETALL sample-app
{
  "server.port": "8100",
  "sample.topic.name": "test",
  "test.property1": "property1"
}
未指定 profile 时,将使用 default

AWS S3 后端

Spring Cloud Config Server 支持将 AWS S3 作为配置属性的后端。您可以通过添加对 AWS Java SDK For Amazon S3 的依赖项来启用此功能。

pom.xml
<dependencies>
	<dependency>
		<groupId>software.amazon.awssdk</groupId>
		<artifactId>s3</artifactId>
	</dependency>
</dependencies>

以下配置使用 AWS S3 客户端访问配置文件。我们可以使用 spring.cloud.config.server.awss3.* 属性选择存储配置的 bucket。

spring:
  profiles:
    active: awss3
  cloud:
    config:
      server:
        awss3:
          region: us-east-1
          bucket: bucket1

也可以指定 AWS URL 来 覆盖 S3 服务的标准端点,使用 spring.cloud.config.server.awss3.endpoint 属性。这支持 S3 的测试版区域以及其他 S3 兼容的存储 API。

使用 默认凭证提供程序链查找凭证。版本化和加密的 bucket 无需进一步配置即可支持。

配置文件以 {application}-{profile}.properties{application}-{profile}.yml{application}-{profile}.json 的形式存储在您的 bucket 中。可以提供一个可选标签来指定文件的目录路径。

未指定 profile 时,将使用 default

AWS Parameter Store 后端

Spring Cloud Config Server 支持将 AWS Parameter Store 作为配置属性的后端。您可以通过添加对 AWS Java SDK for SSM 的依赖项来启用此功能。

pom.xml
<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>ssm</artifactId>
</dependency>

以下配置使用 AWS SSM 客户端访问参数。

spring:
  profiles:
    active: awsparamstore
  cloud:
    config:
      server:
        awsparamstore:
          region: eu-west-2
          endpoint: https://ssm.eu-west-2.amazonaws.com
          origin: aws:parameter:
          prefix: /config/service
          profile-separator: _
          recursive: true
          decrypt-values: true
          max-results: 5

下表描述了 AWS Parameter Store 配置属性。

表 3. AWS Parameter Store 配置属性
属性名称 必需 默认值 备注

region

AWS Parameter Store 客户端要使用的区域。如果未明确设置,SDK 会尝试使用默认区域提供程序链来确定要使用的区域。

endpoint

AWS SSM 客户端入口点的 URL。这可用于为 API 请求指定备用端点。

origin

aws:ssm:parameter

添加到属性源名称的前缀,用于显示其来源。

prefix

/config

用于从 AWS Parameter Store 加载的每个属性在参数层次结构中指示 L1 级别的前缀。

profile-separator

-

将追加的 profile 与上下文名称分隔开的字符串。

recursive

true

指示检索层次结构中所有 AWS 参数的标志。

decrypt-values

true

指示检索所有 AWS 参数并解密其值的标志。

max-results

10

一次 AWS Parameter Store API 调用返回的最大项目数。

使用 默认凭证提供程序链确定 AWS Parameter Store API 凭证。默认行为是返回最新版本,已支持版本化参数。

  • 未指定应用程序时,默认值为 application;未指定 profile 时,默认值为 default

  • awsparamstore.prefix 的有效值必须以正斜杠开头,后跟一个或多个有效路径段,或者为空。

  • awsparamstore.profile-separator 的有效值只能包含点、短划线和下划线。

  • awsparamstore.max-results 的有效值必须在 [1, 10] 范围内。

AWS Secrets Manager 后端

Spring Cloud Config Server 支持将 AWS Secrets Manager 作为配置属性的后端。您可以通过添加对 AWS Java SDK for Secrets Manager 的依赖项来启用此功能。

pom.xml
<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>secretsmanager</artifactId>
</dependency>

以下配置使用 AWS Secrets Manager 客户端访问秘密信息。

spring:
  profiles:
  	active: awssecretsmanager
  cloud:
    config:
      server:
        aws-secretsmanager:
          region: us-east-1
          endpoint: https://us-east-1.console.aws.amazon.com/
          origin: aws:secrets:
          prefix: /secret/foo
          profileSeparator: _

使用 默认凭证提供程序链确定 AWS Secrets Manager API 凭证。

  • 未指定应用程序时,默认值为 application;未指定 profile 时,默认值为 default

  • ignoreLabel 设置为 true 时,labeldefaultLabel 属性都将被忽略。

CredHub 后端

Spring Cloud Config Server 支持将 CredHub 作为配置属性的后端。您可以通过添加对 Spring CredHub 的依赖项来启用此功能。

pom.xml
<dependencies>
	<dependency>
		<groupId>org.springframework.credhub</groupId>
		<artifactId>spring-credhub-starter</artifactId>
	</dependency>
</dependencies>

以下配置使用相互 TLS 访问 CredHub:

spring:
  profiles:
    active: credhub
  cloud:
    config:
      server:
        credhub:
          url: https://credhub:8844

属性应存储为 JSON,例如:

credhub set --name "/demo-app/default/master/toggles" --type=json
value: {"toggle.button": "blue", "toggle.link": "red"}
credhub set --name "/demo-app/default/master/abs" --type=json
value: {"marketing.enabled": true, "external.enabled": false}

所有名称为 spring.cloud.config.name=demo-app 的客户端应用程序都将拥有以下属性:

{
    toggle.button: "blue",
    toggle.link: "red",
    marketing.enabled: true,
    external.enabled: false
}
未指定 profile 时将使用 default,未指定 label 时将使用 master 作为默认值。注意:添加到 application 的值将由所有应用程序共享。
OAuth 2.0

您可以使用 OAuth 2.0 通过 UAA 作为提供程序进行身份验证。

pom.xml
<dependencies>
	<dependency>
		<groupId>org.springframework.security</groupId>
		<artifactId>spring-security-config</artifactId>
	</dependency>
	<dependency>
		<groupId>org.springframework.security</groupId>
		<artifactId>spring-security-oauth2-client</artifactId>
	</dependency>
</dependencies>

以下配置使用 OAuth 2.0 和 UAA 访问 CredHub:

spring:
  profiles:
    active: credhub
  cloud:
    config:
      server:
        credhub:
          url: https://credhub:8844
          oauth2:
            registration-id: credhub-client
  security:
    oauth2:
      client:
        registration:
          credhub-client:
            provider: uaa
            client-id: credhub_config_server
            client-secret: asecret
            authorization-grant-type: client_credentials
        provider:
          uaa:
            token-uri: https://uaa:8443/oauth/token
使用的 UAA client-id 应具有 credhub.read 范围。

复合环境仓库

在某些场景下,您可能希望从多个环境仓库中拉取配置数据。为此,您可以在配置服务器的 application properties 或 YAML 文件中启用 composite profile。例如,如果您想从一个 Subversion 仓库以及两个 Git 仓库中拉取配置数据,您可以为配置服务器设置以下属性:

spring:
  profiles:
    active: composite
  cloud:
    config:
      server:
        composite:
        -
          type: svn
          uri: file:///path/to/svn/repo
        -
          type: git
          uri: file:///path/to/rex/git/repo
        -
          type: git
          uri: file:///path/to/walter/git/repo

使用此配置,优先级由仓库在 composite 键下的列出顺序决定。在上述示例中,Subversion 仓库首先列出,因此在 Subversion 仓库中找到的值将覆盖在其中一个 Git 仓库中找到的相同属性的值。在 rex Git 仓库中找到的值将优先于在 walter Git 仓库中找到的相同属性的值。

如果您只想从各自类型不同的仓库中拉取配置数据,您可以在配置服务器的 application properties 或 YAML 文件中启用相应的 profile,而不是 composite profile。例如,如果您想从单个 Git 仓库和单个 HashiCorp Vault 服务器中拉取配置数据,您可以为配置服务器设置以下属性:

spring:
  profiles:
    active: git, vault
  cloud:
    config:
      server:
        git:
          uri: file:///path/to/git/repo
          order: 2
        vault:
          host: 127.0.0.1
          port: 8200
          order: 1

使用此配置,优先级可以通过 order 属性确定。您可以使用 order 属性指定所有仓库的优先顺序。order 属性的数值越低,优先级越高。仓库的优先顺序有助于解决包含相同属性值的仓库之间的任何潜在冲突。

如果您的复合环境包含 Vault 服务器,如前例所示,则必须在向配置服务器发出的每个请求中包含 Vault 令牌。请参阅 Vault 后端
从环境仓库检索值时发生的任何类型的失败都会导致整个复合环境失败。如果您希望即使某个仓库失败也能继续复合过程,可以将 spring.cloud.config.server.failOnCompositeError 设置为 false
使用复合环境时,所有仓库都包含相同的标签非常重要。如果您的环境类似于前例中的环境,并且您请求带有 master 标签的配置数据,但 Subversion 仓库不包含名为 master 的分支,则整个请求将失败。
自定义复合环境仓库

除了使用 Spring Cloud 的环境仓库之一外,您还可以提供自己的 EnvironmentRepository bean 作为复合环境的一部分。为此,您的 bean 必须实现 EnvironmentRepository 接口。如果您想控制自定义 EnvironmentRepository 在复合环境中的优先级,还应实现 Ordered 接口并覆盖 getOrdered 方法。如果您未实现 Ordered 接口,您的 EnvironmentRepository 将获得最低优先级。

属性覆盖

Config Server 有一个“覆盖”功能,允许操作员为所有应用程序提供配置属性。被覆盖的属性不能被应用程序通过正常的 Spring Boot 钩子意外更改。要声明覆盖,请向 spring.cloud.config.server.overrides 添加一个名称-值对的映射,如下例所示:

spring:
  cloud:
    config:
      server:
        overrides:
          foo: bar

前述示例使所有作为 config client 的应用程序读取 foo=bar,与其自身的配置无关。

配置系统不能强制应用程序以任何特定方式使用配置数据。因此,覆盖不是强制性的。但是,它们确实为 Spring Cloud Config client 提供了有用的默认行为。
通常,带有 ${} 的 Spring 环境占位符可以通过使用反斜杠(\)来转义 ${ 来进行转义(并在客户端解析)。例如,\${app.foo:bar} 解析为 bar,除非应用程序提供了自己的 app.foo
在 YAML 中,您无需转义反斜杠本身。但是,在 properties 文件中,当您在服务器上配置覆盖时,您确实需要转义反斜杠。

您可以通过在远程仓库中设置 spring.cloud.config.overrideNone=true 标志(默认值为 false),将所有覆盖的优先级更改得更像默认值,允许应用程序在环境变量或系统属性中提供自己的值。

使用 Bootstrap 覆盖属性

如果您启用配置优先的 bootstrap,您可以通过在 Config Server 使用的外部环境仓库(例如,Git、Vault、SVN 等)中的应用程序配置中放置两个属性,让客户端设置覆盖 Config Server 的配置。

spring.cloud.config.allowOverride=true
spring.cloud.config.overrideNone=true

启用 Bootstrap 并将这两个属性设置为 true 后,您将能够在客户端应用程序配置中覆盖 Config Server 的配置。

使用占位符覆盖属性

一种更简洁的无需启用配置优先 bootstrap 即可覆盖属性的方法是在来自 Config Server 的配置中使用属性占位符。

例如,如果来自 Config Server 的配置包含以下属性:

hello=${app.hello:Hello From Config Server!}

您可以通过在本地应用程序配置中设置 app.hello 来覆盖来自 Config Server 的 hello 值:

app.hello=Hello From Application!

使用 Profile 覆盖属性

覆盖来自 Config Server 属性的最后一种方法是在客户端应用程序中的 Profile 特定配置文件中指定它们。

例如,如果您有来自 Config Server 的以下配置:

hello="Hello From Config Server!"

您可以通过在 Profile 特定配置文件中设置 hello 并启用该 profile 来在客户端应用程序中覆盖 hello 的值。

application-overrides.properties
hello="Hello From Application!"

在上述示例中,您必须启用 overrides profile。

健康检查指示器

Config Server 自带一个健康检查指示器,用于检查配置的 EnvironmentRepository 是否正常工作。默认情况下,它会向 EnvironmentRepository 请求名为 app、profile 为 default 以及由 EnvironmentRepository 实现提供的默认 label 的应用程序。

您可以配置健康检查指示器以检查更多应用程序以及自定义 profile 和自定义 label,如下例所示:

spring:
  cloud:
    config:
      server:
        health:
          repositories:
            myservice:
              label: mylabel
            myservice-dev:
              name: myservice
              profiles: development

您可以通过将 management.health.config.enabled 设置为 false 来禁用健康检查指示器。

此外,您可以通过设置属性 spring.cloud.config.server.health.down-health-status(默认值为 DOWN)来提供自定义的 down 状态。

安全性

您可以以对您有意义的任何方式保护您的 Config Server(从物理网络安全到 OAuth2 bearer 令牌),因为 Spring Security 和 Spring Boot 支持许多安全安排。

要使用默认的 Spring Boot 配置的 HTTP Basic 安全性,请在 classpath 中包含 Spring Security(例如,通过 spring-boot-starter-security)。默认用户名为 user,密码是随机生成的。随机密码在实践中用途不大,因此我们建议您配置密码(通过设置 spring.security.user.password)并对其进行加密(有关如何执行此操作的说明,请参阅下文)。

Actuator 和安全性

一些平台配置健康检查或类似功能,并指向 /actuator/health 或其他 actuator 端点。如果 actuator 不是 Config Server 的依赖项,则对 /actuator/ 的请求将匹配 Config Server API /{application}/{label},可能泄露敏感信息。在这种情况下,请务必添加 spring-boot-starter-actuator 依赖项,并配置用户,使调用 /actuator/ 的用户无法访问 /{application}/{label} 的 Config Server API。

加密和解密

要使用加密和解密功能,您需要在 JVM 中安装完整强度的 JCE(默认不包含)。您可以从 Oracle 下载“Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files”,并按照安装说明进行操作(基本上,您需要将 JRE lib/security 目录中的两个策略文件替换为您下载的文件)。

如果远程属性源包含加密内容(值以 {cipher} 开头),它们将在通过 HTTP 发送给客户端之前被解密。这种设置的主要优点是属性值在“静止”时(例如,在 git 仓库中)无需明文。如果某个值无法解密,它将从属性源中移除,并添加一个具有相同 key 但前缀为 invalid 且值为“不适用”(通常为 <n/a>)的附加属性。这主要是为了防止密文被用作密码并意外泄露。

如果您为 config client 应用程序设置远程配置仓库,它可能包含类似以下的 application.yml

application.yml
spring:
  datasource:
    username: dbuser
    password: '{cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ'

application.properties 文件中的加密值不得用引号括起来。否则,该值将不会被解密。以下示例显示了有效的格式:

application.properties
spring.datasource.username: dbuser
spring.datasource.password: {cipher}FKSAJDFGYOS8F7GLHAKERGFHLSAJ

您可以安全地将此明文推送到共享 git 仓库,秘密密码将得到保护。

服务器还暴露了 /encrypt/decrypt 端点(假定这些端点是安全的,并且仅由授权代理访问)。如果您编辑远程配置文件,可以使用 Config Server 通过向 /encrypt 端点发送 POST 请求来加密值,如下例所示:

$ curl localhost:8888/encrypt -s -d mysecret
682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
如果您使用 curl 进行测试,请使用 --data-urlencode(代替 -d)并在要加密的值前加上 =(curl 需要这样),或设置显式 Content-Type: text/plain 以确保 curl 在存在特殊字符('+' 特别棘手)时正确编码数据。
确保不要将任何 curl 命令统计信息包含在加密值中,这就是示例使用 -s 选项来静默它们的原因。将值输出到文件可以帮助避免此问题。

反向操作也通过 /decrypt 可用(前提是服务器配置了对称 key 或完整的密钥对),如下例所示:

$ curl localhost:8888/decrypt -s -d 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
mysecret

将加密值加上 {cipher} 前缀,然后将其放入 YAML 或 properties 文件中,再提交并推送到远程(可能不安全)存储。

/encrypt/decrypt 端点也接受 /*/{application}/{profiles} 形式的路径,当客户端调用主环境资源时,可用于按应用程序(名称)和按 profile 控制加密。

要以这种粒度控制加密,您还必须提供一个类型为 TextEncryptorLocator@Bean,它可以为每个名称和配置文件创建不同的加密器。默认提供的加密器不会这样做(所有加密都使用相同的密钥)。

spring 命令行客户端(安装了 Spring Cloud CLI 扩展)也可以用于加密和解密,如以下示例所示

$ spring encrypt mysecret --key foo
682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
$ spring decrypt --key foo 682bc583f4641835fa2db009355293665d2647dade3375c0ee201de2a49f7bda
mysecret

要在文件中使用密钥(例如用于加密的 RSA 公钥),请在密钥值前加上 "@" 并提供文件路径,如以下示例所示

$ spring encrypt mysecret --key @${HOME}/.ssh/id_rsa.pub
AQAjPgt3eFZQXwt8tsHAVv/QHiY5sI2dRcR+...
--key 参数是必需的(尽管有 -- 前缀)。

密钥管理

Config Server 可以使用对称(共享)密钥或非对称密钥(RSA 密钥对)。非对称密钥在安全性方面更优越,但使用对称密钥通常更方便,因为在 application.properties 中只需要配置一个属性值。

要配置对称密钥,您需要将 encrypt.key 设置为一个秘密字符串(或使用 ENCRYPT_KEY 环境变量以避免将其暴露在纯文本配置文件中)。

如果您在类路径中包含 spring-cloud-starter-bootstrap 或将 spring.cloud.bootstrap.enabled=true 设置为系统属性,则需要在 bootstrap.properties 中设置 encrypt.key
您不能使用 encrypt.key 配置非对称密钥。

要配置非对称密钥,请使用密钥库(例如,通过 JDK 自带的 keytool 工具创建)。密钥库属性是 encrypt.keyStore.*,其中 * 等于

属性 描述

encrypt.keyStore.location

包含一个 Resource 位置

encrypt.keyStore.password

保存用于解锁密钥库的密码

encrypt.keyStore.alias

标识要使用的密钥库中的密钥

encrypt.keyStore.type

要创建的 KeyStore 类型。默认为 jks

加密使用公钥完成,解密需要私钥。因此,原则上,如果您只想加密(并准备好自己在本地用私钥解密),您可以在服务器中仅配置公钥。实际上,您可能不想在本地解密,因为它将密钥管理过程分散到所有客户端,而不是集中在服务器中。另一方面,如果您的配置服务器相对不安全,并且只有少数客户端需要加密属性,那么这是一个有用的选项。

创建测试密钥库

要创建用于测试的密钥库,可以使用类似于以下内容的命令

$ keytool -genkeypair -alias mytestkey -keyalg RSA \
  -dname "CN=Web Server,OU=Unit,O=Organization,L=City,S=State,C=US" \
  -keypass changeme -keystore server.jks -storepass letmein
使用 JDK 11 或更高版本时,在使用上述命令时可能会收到以下警告。在这种情况下,您可能需要确保 keypassstorepass 的值匹配。
Warning:  Different store and key passwords not supported for PKCS12 KeyStores. Ignoring user-specified -keypass value.

server.jks 文件放在类路径中(例如),然后在 Config Server 的 bootstrap.yml 中,创建以下设置

encrypt:
  keyStore:
    location: classpath:/server.jks
    password: letmein
    alias: mytestkey
    secret: changeme

使用多个密钥和密钥轮换

除了加密属性值中的 {cipher} 前缀之外,Config Server 还会查找在(Base64 编码的)密文开始之前的零个或多个 {name:value} 前缀。这些密钥被传递给 TextEncryptorLocator,它可以执行所需的任何逻辑来为密文定位一个 TextEncryptor。如果您配置了密钥库(encrypt.keystore.location),默认的定位器会查找由 key 前缀提供的别名密钥,其密文类似于

foo:
  bar: `{cipher}{key:testkey}...`

定位器查找名为 "testkey" 的密钥。也可以在前缀中使用 {secret:…​} 值来提供秘密。但是,如果未提供秘密,默认是使用密钥库密码(这是您构建密钥库且未指定秘密时获得的结果)。如果您提供了秘密,则还应该使用自定义的 SecretLocator 来加密秘密。

当密钥仅用于加密少量配置数据(即未在其他地方使用)时,从加密角度来看,密钥轮换几乎没有必要。但是,您可能偶尔需要更改密钥(例如,在安全漏洞事件中)。在这种情况下,所有客户端都需要更改其源代码配置文件(例如,在 git 中),并在所有密文中使用新的 {key:…​} 前缀。请注意,客户端需要首先检查密钥别名在 Config Server 密钥库中是否可用。

如果您希望 Config Server 处理所有加密和解密,{name:value} 前缀也可以作为纯文本添加到发送到 /encrypt 端点的请求体中。

提供加密属性

有时您希望客户端在本地解密配置,而不是在服务器中进行。在这种情况下,如果您提供了用于定位密钥的 encrypt.* 配置,您仍然可以拥有 /encrypt/decrypt 端点,但您需要在 bootstrap.[yml|properties] 中明确关闭对出站属性的解密,方法是设置 spring.cloud.config.server.encrypt.enabled=false。如果您不关心这些端点,只需不配置密钥或启用标志即可。

提供其他格式

环境端点提供的默认 JSON 格式非常适合 Spring 应用程序使用,因为它直接映射到 Environment 抽象。如果您愿意,可以通过向资源路径添加后缀(".yml"、".yaml" 或 ".properties")来以 YAML 或 Java 属性格式使用相同的数据。这对于不关心 JSON 端点结构或其提供额外元数据的应用程序(例如,不使用 Spring 的应用程序)可能很有用,因为这种方法更简单。

YAML 和属性表示有一个额外的标志(作为布尔查询参数 resolvePlaceholders 提供),用于指示在可能的情况下,应在渲染输出之前解析源文档中的占位符(采用标准的 Spring ${…​} 形式)。这对于不了解 Spring 占位符约定的消费者来说是一个有用的功能。

使用 YAML 或属性格式存在局限性,主要与元数据丢失有关。例如,JSON 以有序属性源列表的形式构建,其名称与源相关联。YAML 和属性形式被合并为一个映射,即使值的来源有多个源,原始源文件的名称也会丢失。此外,YAML 表示不一定忠实地反映备份仓库中的 YAML 源。它是由平面属性源列表构建的,并且必须对键的形式做出假设。

提供纯文本

除了使用 Environment 抽象(或其 YAML 或属性格式的替代表示)之外,您的应用程序可能还需要根据其环境定制的通用纯文本配置文件。Config Server 通过 /{application}/{profile}/{label}/{path} 的额外端点提供这些文件,其中 applicationprofilelabel 与常规环境端点具有相同的含义,而 path 是指向文件名的路径(例如 log.xml)。此端点的源文件的查找方式与环境端点相同。属性文件和 YAML 文件使用相同的搜索路径。但是,不会聚合所有匹配的资源,只会返回第一个匹配的资源。

找到资源后,将使用提供的应用程序名称、配置文件和标签的有效 Environment 来解析正常格式(${…​})的占位符。通过这种方式,资源端点与环境端点紧密集成。

与环境配置的源文件一样,profile 用于解析文件名。因此,如果您想要一个特定于配置文件的文件,可以通过一个名为 logback-development.xml 的文件来解析 /*/development/*/logback.xml(优先于 logback.xml)。
如果您不想提供 label 并让服务器使用默认标签,您可以提供 useDefaultLabel 请求参数。因此,前面关于 default 配置文件的示例可以是 /sample/default/nginx.conf?useDefaultLabel

目前,Spring Cloud Config 可以为 git、SVN、原生后端和 AWS S3 提供纯文本。对 git、SVN 和原生后端的支持是相同的。AWS S3 的工作方式略有不同。以下部分显示了它们各自的工作方式

提供二进制文件

为了从配置服务器提供二进制文件,您需要发送一个 Accept 头部,其值为 application/octet-stream

Git、SVN 和原生后端

考虑以下针对 GIT 或 SVN 仓库或原生后端的示例

application.yml
nginx.conf

nginx.conf 可能类似于以下清单

server {
    listen              80;
    server_name         ${nginx.server.name};
}

application.yml 可能类似于以下清单

nginx:
  server:
    name: example.com
---
spring:
  profiles: development
nginx:
  server:
    name: develop.com

/sample/default/master/nginx.conf 资源可能如下所示

server {
    listen              80;
    server_name         example.com;
}

/sample/development/master/nginx.conf 可能如下所示

server {
    listen              80;
    server_name         develop.com;
}

AWS S3

要启用为 AWS S3 提供纯文本,Config Server 应用程序需要包含对 io.awspring.cloud:spring-cloud-aws-context 的依赖。有关如何设置该依赖项的详细信息,请参阅 Spring Cloud AWS Reference Guide。此外,在使用 Spring Cloud AWS 和 Spring Boot 时,包含 自动配置依赖项 会很有用。然后,您需要配置 Spring Cloud AWS,如 Spring Cloud AWS Reference Guide 中所述。

解密纯文本

默认情况下,纯文本文件中的加密值不会被解密。为了启用纯文本文件的解密,请在 bootstrap.[yml|properties] 中设置 spring.cloud.config.server.encrypt.enabled=truespring.cloud.config.server.encrypt.plainTextEncrypt=true

解密纯文本文件仅支持 YAML、JSON 和 properties 文件扩展名。

如果启用了此功能,并且请求了不受支持的文件扩展名,则文件中的任何加密值都不会被解密。

嵌入式 Config Server

Config Server 作为独立应用程序运行效果最佳。但是,如有需要,您可以将其嵌入到另一个应用程序中。为此,请使用 @EnableConfigServer 注解。在这种情况下,一个名为 spring.cloud.config.server.bootstrap 的可选属性可能很有用。它是一个标志,指示服务器是否应从其自己的远程仓库配置自身。默认情况下,此标志是关闭的,因为它可能会延迟启动。但是,当嵌入在另一个应用程序中时,以与任何其他应用程序相同的方式初始化是合理的。将 spring.cloud.config.server.bootstrap 设置为 true 时,您还必须使用 组合环境仓库配置。例如

spring:
  application:
    name: configserver
  profiles:
    active: composite
  cloud:
    config:
      server:
        composite:
          - type: native
            search-locations: ${HOME}/Desktop/config
        bootstrap: true
如果您使用 bootstrap 标志,则需要在 bootstrap.yml 中配置 Config Server 的名称和仓库 URI。

要更改服务器端点的位置,您可以(可选)设置 spring.cloud.config.server.prefix(例如,/config),以在某个前缀下提供资源。此前缀应以 / 开头,但不以 / 结尾。它应用于 Config Server 中的 @RequestMappings(即在 Spring Boot 的 server.servletPathserver.contextPath 前缀之下)。

如果您想直接从后端仓库读取应用程序的配置(而不是从配置服务器),您基本上需要一个没有端点的嵌入式配置服务器。您可以通过不使用 @EnableConfigServer 注解来完全关闭端点(设置 spring.cloud.config.server.bootstrap=true)。

推送通知和 Spring Cloud Bus

许多源代码仓库提供商(例如 Github、Gitlab、Gitea、Gitee、Gogs 或 Bitbucket)通过 webhook 通知您仓库的更改。您可以通过提供商的用户界面将 webhook 配置为一个 URL 和一组您感兴趣的事件。例如,Github 使用 POST 请求到 webhook,请求体是一个包含提交列表的 JSON,并且头部 (X-Github-Event) 设置为 push。如果您添加对 spring-cloud-config-monitor 库的依赖,并在 Config Server 中激活 Spring Cloud Bus,则会启用 /monitor 端点。

当 webhook 被激活时,Config Server 会发送一个定向到它认为可能已更改的应用程序的 RefreshRemoteApplicationEvent。更改检测可以进行策略化。但是,默认情况下,它查找与应用程序名称匹配的文件中的更改(例如,foo.properties 定向到 foo 应用程序,而 application.properties 定向到所有应用程序)。当您想要覆盖此行为时使用的策略是 PropertyPathNotificationExtractor,它接受请求头部和请求体作为参数,并返回一个已更改的文件路径列表。

默认配置与 Github、Gitlab、Gitea、Gitee、Gogs 或 Bitbucket 开箱即用。除了来自 Github、Gitlab、Gitee 或 Bitbucket 的 JSON 通知外,您还可以通过向 /monitor 发送 POST 请求并使用格式为 path={application} 的表单编码请求体参数来触发更改通知。这样做会将通知广播到与 {application} 模式匹配的应用程序(该模式可以包含通配符)。

只有当 Config Server 和客户端应用程序都激活了 spring-cloud-bus 时,RefreshRemoteApplicationEvent 才会传输。
默认配置还会检测本地 git 仓库中的文件系统更改。在这种情况下,不使用 webhook。但是,只要您编辑配置文件,就会广播刷新通知。

AOT 和 Native Image 支持

4.0.0 起,Spring Cloud Config Server 支持 Spring AOT 转换。然而,目前尚不支持 GraalVM Native Image。实现 Native Image 支持被 graal#5134 阻止,并且可能需要完成 https://github.com/graalvm/taming-build-time-initialization 上的工作才能修复。

Spring Cloud Config Client

Spring Boot 应用程序可以立即利用 Spring Config Server(或应用程序开发人员提供的其他外部属性源)。它还获得了一些与 Environment 更改事件相关的额外有用功能。

Spring Boot 配置数据导入

Spring Boot 2.4 引入了一种通过 spring.config.import 属性导入配置数据的新方法。这现在是绑定到 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 配置数据分两步解析配置。首先,它使用 default profile 加载所有配置。这允许 Spring Boot 收集所有可能激活任何其他 profile 的配置。收集到所有激活的 profile 后,它将为活动的 profile 加载任何额外的配置。因此,您可能会看到向 Spring Cloud Config Server 发出多个请求来获取配置。这是正常的,是 Spring Boot 使用 spring.config.import 加载配置的方式所带来的副作用。在 Spring Cloud Config 的早期版本中,只发出一个请求,但这表示您无法从 Config Server 获取的配置中激活 profile。现在,只需使用 'default' profile 发出的额外请求使这成为可能。

对于通过 spring.config.import 导入的 Spring Boot 配置数据方法,不需要 bootstrap 文件(properties 或 yaml)。

Config First Bootstrap

要使用连接到 Config Server 的传统 bootstrap 方式,必须通过属性或 spring-cloud-starter-bootstrap Starter 启用 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")。

Discovery First Lookup

除非您使用 Config First Bootstrap,否则您需要在配置属性中包含带有 optional: 前缀的 spring.config.import 属性。例如,spring.config.import=optional:configserver:

如果您使用 DiscoveryClient 实现,例如 Spring Cloud Netflix 和 Eureka 服务发现或 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)。

Discovery Client 实现都支持某种元数据映射(例如,对于 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 的 Discovery First Bootstrap

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

Config Client 快速失败

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

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

Config Client 重试

如果您期望 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

要完全控制重试行为并使用旧版 bootstrap,请添加一个类型为 RetryOperationsInterceptor 且 ID 为 configServerRetryInterceptor@Bean。Spring Retry 提供了一个支持创建此类 Bean 的 RetryInterceptorBuilder

使用 spring.config.import 的 Config Client 重试

重试功能与 Spring Boot 的 spring.config.import 语句和正常属性一起使用。但是,如果 import 语句位于 profile 中,例如 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 label、分支名称或提交 ID。Label 也可以以逗号分隔的列表形式提供。在这种情况下,列表中的项会逐个尝试,直到成功。这种行为在处理 feature 分支时很有用。例如,您可能希望将配置标签与您的分支对齐,但使其成为可选的(在这种情况下,使用 spring.cloud.config.label=myfeature,develop)。

为 Config Server 指定多个 URL

当您部署了多个 Config Server 实例,并期望有时一个或多个实例不可用或无法响应请求(例如 Git 服务器宕机)时,为了确保高可用性,您可以指定多个 URL(在 spring.cloud.config.uri 属性下以逗号分隔列表形式),或者让所有实例在像 Eureka 这样的服务注册中心注册(如果使用 Discovery-First 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 安全性,目前只有当您在 spring.cloud.config.uri 属性下指定的每个 URL 中嵌入凭据时,才支持每个 Config Server 的身份验证凭据。如果您使用任何其他类型的安全机制,则(目前)不支持每个 Config Server 的身份验证和授权。

配置超时

如果要配置超时阈值

  • 读超时可以使用属性 spring.cloud.config.request-read-timeout 进行配置。

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

安全性

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

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}

如果配置服务器需要客户端 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 以启用配置客户端 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 context) 中获取并注入它)。

健康指示器

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

提供自定义 RestTemplate

在某些情况下,您可能需要自定义客户端向配置服务器发出的请求。通常,这涉及传递特殊的 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 作为配置服务器的后端时,客户端需要提供一个令牌,供服务器从 Vault 中检索值。这个令牌可以通过在 bootstrap.yml 中设置 spring.cloud.config.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。

AOT 和 native image 支持不适用于配置优先引导(使用 spring.config.use-legacy-processing=true)。
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 context) 中使用的属性)在构建时和运行时应设置为相同的值,以避免意外行为。
由于 Config Client 在从 native image 启动时连接到正在运行的数据源(例如 Config Server),快速启动时间将会因网络通信所需的时间而减慢。

附录

可观测性元数据

可观测性 - 指标

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

环境仓库 (Environment Repository)

围绕 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

在开始观测后添加的 KeyValue 可能在 *.active 指标中缺失。
Micrometer 内部使用 nanoseconds 作为基本单位。然而,每个后端确定实际的基本单位。(即 Prometheus 使用 seconds)

封闭类的完全限定名 org.springframework.cloud.config.server.environment.DocumentedConfigObservation

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

名称

描述

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 前缀开头!
表 5. 标签键

名称

描述

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

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

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

EnvironmentRepository 的实现。

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

正在查询属性的标签。

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

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