Spring Boot + Spring Cloud Config - 如何从 Git 外部配置添加更多配置文件

Posted

技术标签:

【中文标题】Spring Boot + Spring Cloud Config - 如何从 Git 外部配置添加更多配置文件【英文标题】:Spring Boot + Spring Cloud Config - How to add more profiles from the Git external configuration 【发布时间】:2016-07-29 16:52:24 【问题描述】:

我在 Spring Boot 应用程序中有这个配置:

spring:
  application:
    name: my-app
  profiles:
    active: $ENVIRONMENT
  cloud:
    config:
     uri: http://localhost:8888

我的配置服务器读取以下文件:

my-app-dev.yaml

prop: dev property

my-app-pro.yaml

prop: pro property.

我启动 spring boot 应用设置 -DENVIRONMENT=dev,正确加载 dev 外部 Git 属性。

当我在假设一个控制器中注入环境并执行env.getActiveProfiles() 时,我得到了预期的“dev”。

我想从 git 配置中添加更多配置文件。例如:

my-app-dev.yaml

prop: dev property
spring:
  active:
    profiles: dev,business1

my-app-pro.yaml

prop: dev property
spring:
  active:
    profiles: pro,business2

这样env.getActiveProfiles() 返回["dev","business1"]。然而它返回的是初始的"dev"

这是怎么做到的?

更新:

按照 Dave Syer 的建议,我尝试在 Git 文件中使用 spring.profiles.include,但新配置文件未添加到环境中:

my-app-dev.yaml

prop: dev property
spring:
  profiles:
    include: business1

my-app-pro.yaml

prop: dev property
spring:
  profiles:
    include: business2

environment.getActiveProfiles() ---> "dev"

【问题讨论】:

你试过spring.profiles.include (docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/…)吗? @DaveSyer,我刚试过,但注入的Environment.getActiveProfiles() 只返回原始的$ENVIRONMENT(开发)配置文件。 我不知道你是如何测试这个的,但它对我来说可以按预期工作。为了清楚起见:您无法通过编辑远程配置文件来更改客户端应用程序中的活动配置文件,但您可以更改配置服务器中加载的内容(我认为这就是您想要的)。因此,如果您加载 /my-app/dev,您应该会在结果中看到来自 my-app-business1.yml 的配置。 @DaveSyer 感谢您的回答。我不想更改活动配置文件,我想使用 Git 存储库中定义的配置文件将配置文件添加到应用程序,以便 env.getActiveProfiles() 返回来自应用程序内部 application.yml (spring: active: profiles: dev) 的 dev和来自 Git myapp-dev.yaml (spring: profiles: include: business1) 的 business1。也许我的项目有问题。我将从头开始使用一个基本的 Spring Boot 应用程序再次检查它并在 GitHub 中提供它,以防它不起作用。 配置服务器中属性文件的选择基于传入应用程序提供的活动配置文件。因此,当您将 dev 设置为活动配置文件时,configserver 将发送 my-app-dev.yml。从这个角度来看,一旦文件被识别,我们就完成了配置文件。因此,在选定文件中再次定义配置文件会令人困惑。由于我们可以在应用程序端包含多个配置文件,我希望 configserver 提供相同数量的属性文件。您可以尝试在 git 中创建 my-app-dev.yml 和 my-app-business1.yml 并在应用端启用这两个配置文件吗? 【参考方案1】:

将你的 spring-boot 更新到 1.5.4。

我在我的 Mac 上测试了同样的情况,我发现不同版本的 spring 表现不同。

当我将 Spring Boot 1.3.8.RELEASE 与 Spring Cloud Brixton.SR7 一起使用时,我将 [dev] 配置文件作为活动配置文件(也与 Spring Boot 1.4.5.RELEASE 一起使用)

当我将 Spring Boot 1.5.4.RELEASE 与 Spring Cloud Dalston.SR1 一起使用时,我得到了 [business1, dev] 个人资料作为活动个人资料

所以我认为这是 Spring Boot 1.3.x 和 1.4.x 中的一个错误

【讨论】:

是的,升级后它现在可以工作了,谢谢你告诉我!

以上是关于Spring Boot + Spring Cloud Config - 如何从 Git 外部配置添加更多配置文件的主要内容,如果未能解决你的问题,请参考以下文章

Spring Cloud总结29.Zuul的FallBack回退机制

将已有的spring app迁移到spring-boot,手动配置spring-boot?

为啥 Spring Boot 应用程序 pom 同时需要 spring-boot-starter-parent 和 spring-boot-starter-web?

《02.Spring Boot连载:Spring Boot实战.Spring Boot核心原理剖析》

spring-boot-quartz, 依赖spring-boot-parent

spring-boot系列:初试spring-boot