14.3 消费共享的配置

Spring Cloud Config server 还提供了一个客户端库。只要 Spring Boot 应用程序中包含这个库,就可以作为 Config Server 的客户端。将一个 Spring Boot 应用程序转换为 Config Server 客户端的最简单方法是,将以下依赖项添加到项目的 Maven 依赖中:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

使用 Spring Initializr 中也可添加此依赖项,只需勾选 Config Client 复选框。应用程序运行时自动配置将启动,会自动指定属性来源,以便从 Config Server 中获取属性。默认情况下,会假设 Config Server 正在本地主机上运行,并侦听端口 8888。 如果不是这样,可以通过设置 spring.cloud.config.uri.property 属性,来配置 Config Server 的位置:

spring:
  cloud:
    config:
      uri: http://config.tacocloud.com:8888

需要澄清一点,这个属性必须设置在,要成为 Config Server 客户端的应用程序的本地。比如在 application.yml 或者 application.properties 文件中,并与微服务一起打包和部署。

现在您有了一个集中式的 Config Server,几乎所有的配置都将从那里得到。每个微服务不需要携带太多自己的配置。通常,您只需设置 spring.cloud.config.uri 来指定 Config Server 的位置,以及 spring.application.name 让 Config Server 进行应用识别。

哪一个优先:Config Server 还是 Service Registry?

您可以设置您的微服务从 Config Server 获取 Eureka 服务注册中心信息。这是避免在整个应用中相互传播服务注册中心配置的常用方法。

还可以让 Config Server 向 Eureka 注册,让每个微服务像发现任何其他服务一样发现 Config Server。如果你喜欢这个方式,需要将Config Server 的 spring.cloud.config.discovery.enabled 属性设置为 true。这样, Config Server 将用名称 configserver 在 Eureka 中注册自己。

这种方法的缺点是,每个服务在启动时要进行两个调用:一个到 Eureka 中查找 Config Server,然后再到 Config Server 中 获取配置数据。

当应用程序启动时,Config Server 客户端指定属性源,并向 Config Server 发出请求。不管它收到什么属性,都会设置到应用程序环境变量中。更重要的是,这些属性将被缓存;即使 Config Server 关闭了,它们也可用。(我们将在第 14.6 节中介绍,在属性更改时刷新属性的一些方法。)

到目前为止,您让 Config Server 提供的配置还相当简单,这些配置指定给所有微服务。但有时您需要对某个应用程序启用特定配置,或者只有在应用程序使用特定的 profile 时才有效。让我们再来看看 Config Server 更多的使用方式,看看如何提供特定于应用程序或 profile 的配置。

results matching ""

    No results matching ""