Read values from consul while bootstrap spring boot

有些话、适合烂在心里 提交于 2019-12-25 01:09:59

问题


I have question is there any way to retrieve certain values and inject them to bootstrap.yml while application is coming up.

I have configuration file like this:

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

For example, I need to configure embedded tomcat port, or DB credentials, I don't want to put it hardcoded in .yml properties file, instead I want to put some variable name in .yml so Spring will go and bring value from Consul. Is it possible?


回答1:


You can use Spring Cloud Consul Config project that helps to load configuration into the Spring Environment during the special "bootstrap" phase.

3 steps:

  1. add pom dependency: spring-cloud-starter-consul-config
  2. enable consul config: spring.cloud.consul.config.enabled=true
  3. add some config in consul kv in specific folder, such as key: config/testConsulApp/server.port, value:8081

and then start the sample web app, it will listen 8081.

more detail at spring cloud consul doc.

and demo code here



来源:https://stackoverflow.com/questions/54615291/read-values-from-consul-while-bootstrap-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!