您如何在 bootstrap 文件中正确设置不同的 Spring 配置文件(用于 Spring 启动以针对不同的云配置服务器)?

How do you properly set different Spring profiles in bootstrap file (for Spring Boot to target different Cloud Config Servers)?

我们每个环境都有不同的配置服务器。每个 spring 启动应用程序都应该以其相应的配置服务器为目标。我试图通过在 bootstrap.properties 文件中设置配置文件来实现这一点,例如:

spring.application.name=app-name
spring.cloud.config.uri=http://default-config-server.com

---
spring.profiles=dev
spring.cloud.config.uri=http://dev-config-server.com

---
spring.profiles=stage
spring.cloud.config.uri=http://stage-config-server.com

---
spring.profiles=prod
spring.cloud.config.uri=http://prod-config-server.com

然后我设置了 cla -Dspring.profiles.active=dev 但加载的配置服务器始终是文件中设置的最后一个(即 prod 配置服务器将在上述设置中加载,然后如果 prod 被删除,阶段将被加载)。

是否可以为云配置服务器设置 bootstrap 配置文件?我关注了 ,但似乎无法正常工作。对于它的价值,这些配置文件非常适合加载正确的配置(即如果开发配置文件处于活动状态,app-name-dev.properties 将加载),但不会从正确的配置服务器中提取。

在单个文件中指定不同的配置文件仅支持 YAML 文件,不适用于 属性 文件。对于 属性 文件,指定特定环境 bootstrap-[profile].properties 以覆盖默认 bootstrap.properties 的属性。

因此,在您的情况下,您将获得 4 个文件 bootstrap.propertiesbootstrap-prod.propertiesbootstrap-stage.propertiesbootstrap-dev.properties

然而,除此之外,您还可以仅提供默认值 bootstrap.properties,并在启动应用程序时通过将 -Dspring.cloud.config.uri=<desired-uri> 传递给您的应用程序来覆盖 属性。

java -jar <your-app>.jar -Dspring.cloud.config.uri=<desired-url>

这将优先于默认配置值。

I solved a similar problem with an environment variable in Docker. 

bootstrap.yml

spring:
  application:
    name: dummy_service
  cloud:
    config:
      uri: ${CONFIG_SERVER_URL:http://localhost:8888/}
      enabled: true
  profiles:
    active: ${SPR_PROFILE:dev}

Docker文件

ENV CONFIG_SERVER_URL=""
ENV SPR_PROFILE=""

Docker-compose.yml

version: '3'

services:

  dummy:
    image: xxx/xxx:latest
    restart: always
    environment:  
      - SPR_PROFILE=docker
      - CONFIG_SERVER_URL=http://configserver:8888/
    ports:
      - 8080:8080
    depends_on:
      - postgres
      - configserver
      - discovery

@LarryW(我无法回答相同的评论):

我想显式添加 属性 的好处是它允许您在不设置环境变量的情况下添加默认值(在本例中为“dev”)。