首页 > 解决方案 > 在运行时具有动态引导 URI 的 Spring Cloud Config 客户端?

问题描述

给定一个配置客户端 bootstrap.yml:

spring:
  ...
  cloud:
    config:
      uri: ${SPRING_CONFIG_URI:http://localhost:9000}
      fail-fast: true

环境变量SPRING_CONFIG_URI需要在运行时设置。我们可以再讨论一下这个代码的味道,但是对于这个练习,这个 URI 只有在服务启动时才知道(它与获取随机 SRV 记录有关)。

是否有一种 Spring 方式来设置/覆盖某些bootstrap.yaml参数?

这是我尝试过的:

@SpringBootApplication
public class Application {
    public static void main( String[] args ) throws Exception
    {
        String configServerPort = DnsHelper.resolveSrv("configserver.local");

        // This doesn't work
        System.setProperty("SPRING_CONFIG_URI", configServerPort);

        // This doesn't work
        // Use reflection to change the in-memory environment variables
        // @see https://stackoverflow.com/a/7201825/1938889
        setEnv( Map.of( "SPRING_CONFIG_URI", configServerPort ) );

        // After the environment variable is set, then start the service
        Application.run( Application.class, args );
    }
    ...

标签: linuxwindowsspring-bootenvironment-variables

解决方案


推荐阅读