在 spring 云中的 bootstrap.yml 上设置配置文件以针对不同的配置服务器

Set profile on bootstrap.yml in spring cloud to target different config server

我使用 docker 组合 运行 我所有的微服务。对于每项服务,我都给它一个简短的主机名。

version: '2'

services: 
  config:
    image: springbox-config-server
    restart: always
    ports:
     - "8890:8890"

  discovery:
    image: springbox-eureka
    restart: always
    ports:
     - "8763:8763"

因此,在我的微服务中,我必须使用短主机名来定位配置服务器。

spring:
  application:
    name: myservice
  cloud:
    config:
      uri: http://config:8890
      fail-fast: true

但是,当我 运行 在我的 IDE 本地 docker 时,短主机名无法解析。

所以我正在寻找一种解决方案,以根据我的环境针对不同的配置服务器。

我找到了解决办法。基本上,我们使用 spring 配置文件来丰富 bootstrap 文件。例如

spring:
  application:
    name: myservice
  cloud:
    config:
      uri: http://config:8890
      fail-fast: true

---
spring:
  profiles: development
  cloud:
    config:
      uri: http://localhost:8890

好消息是我们不必重写配置文件中的所有属性。默认属性是继承的。例如,当启用开发配置文件时,我的应用程序名称继承自默认名称 always myservice。

要激活配置文件,请使用以下命令启动服务 属性

-Dspring.profiles.active=development