【问题标题】:How do you properly set different Spring profiles in bootstrap file (for Spring Boot to target different Cloud Config Servers)?您如何在引导文件中正确设置不同的 Spring 配置文件(让 Spring Boot 以不同的云配置服务器为目标)?
【发布时间】:2017-04-20 07:04:59
【问题描述】:

每个环境都有不同的配置服务器。每个 Spring Boot 应用程序都应该针对其相应的配置服务器。我试图通过在 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,将加载 stage )。

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

【问题讨论】:

  • 这只适用于 yaml 文件而不是属性文件 (afaik)。只需添加 bootstrap-[profile].propertiesbootstrap-dev.properties ,它将包含所需的(覆盖)配置。

标签: java spring-boot spring-cloud-config spring-profiles


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    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}
    

    Dockerfile

    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
    

    【讨论】:

    • 为什么不在 Docker 中设置SPRING_PROFILES_ACTIVE(在环境中),而跳过 bootstrap.yml 中的spring.profiles.active
    【解决方案3】:

    在单个文件中指定不同的配置文件仅支持 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>
    

    这将优先于默认配置值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-24
      • 2017-12-21
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-15
      相关资源
      最近更新 更多