在 bootstrap spring 引导时从 consul 读取值

Read values from consul while bootstrap spring boot

我想知道有没有什么方法可以在应用程序启动时检索某些值并将它们注入 bootstrap.yml。

我有这样的配置文件:

spring:
  application:
    name: myApp

  cloud:
    consul:
      enabled: true
      host: localhost
      port: 8500
      config:
        enabled: true

  datasource:
    url: jdbc:oracle:thin:@localhost:1111:XXXX
    username: ${nameOfVariable1}
    password: ${nameOfVariable1}
    driver-class-name: oracle.jdbc.OracleDriver

例如,我需要配置嵌入式 tomcat 端口或数据库凭据,我不想将其硬编码到 .yml 属性文件中,而是想将一些变量名放入 .yml 中所以 Spring 会去 Consul 带来价值。可能吗?

您可以使用 Spring Cloud Consul Config 项目帮助在特殊的 "bootstrap" 阶段将配置加载到 Spring 环境中。

3 个步骤:

  1. 添加pom依赖:spring-cloud-starter-consul-config
  2. 启用领事配置:spring.cloud.consul.config.enabled=true
  3. 在特定文件夹的 consul kv 中添加一些配置,例如密钥:config/testConsulApp/server.port、value:8081

然后启动示例 Web 应用程序,它将侦听 8081。

详情请见 spring cloud consul doc

demo code here