如何使用 Spring 配置服务设置本地配置属性

How to set local config properties with Spring Config Service

所以我最近学习了 Spring Cloud 这个很棒的配置服务,经过一番努力,我能够设置我们的分布式应用程序,多个节点从一个配置服务器读取配置属性。

但是我不知道如何解决的一个问题是即使大多数 props 在多个节点上都是相同的,一些 props 需要本地版本并且我不知道如何将本地 prop 与配置服务一起设置。

例如这是我的 bootstrap.properties,

spring.cloud.config.uri=${config.server:http://localhost:8888}
spring.application.name=worker

如果我在 bootstrap.properties 下或在单独的 application.properties 文件中添加额外的道具,我可以在执行器的环境端点下看到它们,就像这样,

configService:file:///home/me/work/config-test/worker.properties: 
{
    server.timeout: "100"
},

applicationConfig: [classpath:/application.properties]: {
    server.timeout: "50"
},

在我的应用程序中,server.timeout 现在将始终为 100,我不知道当我使用像这样的集中配置服务时如何引用本地值?

好的,经过更多研究,我找到了答案。来自 https://docs.pivotal.io/spring-cloud-services/config-server/configuration-clients.html

A Spring application can use a Config Server as a property source. Properties from a Config Server will override those defined locally (e.g. via an application.yml in the classpath).

所以正确的做法是将任何客户端 属性 排除在配置服务之外。这对我来说也意味着对于这样的属性,没有办法有一个默认值,只有在客户端值出现时才会被覆盖,这将是一件好事。

来自官方文档的Overriding the Values of Remote Properties部分:

The property sources that are added to you application by the bootstrap context are often "remote" (e.g. from a Config Server), and by default they cannot be overridden locally, except on the command line. If you want to allow your applications to override the remote properties with their own System properties or config files, the remote property source has to grant it permission by setting spring.cloud.config.allowOverride=true (it doesn’t work to set this locally).

Once that flag is set there are some finer grained settings to control the location of the remote properties in relation to System properties and the application’s local configuration: spring.cloud.config.overrideNone=true to override with any local property source, and spring.cloud.config.overrideSystemProperties=false if only System properties and env vars should override the remote settings, but not the local config files.

因此,您可以在远程 application.yml(例如远程 git 存储库)中设置以下配置,以允许本地覆盖远程属性。

spring:
  cloud:
    config:
      allowOverride: true
      overrideNone: true
      overrideSystemProperties: false