首页 > 解决方案 > 启动后更改 Spring Cloud Config 服务器 uri

问题描述

我引导我的springboot应用程序指向默认配置服务器以在启动时获取配置道具,配置服务器将spring.cloud.config.uri(不要问我为什么:D)更改为指向不同的配置服务器......当我调用/actuator/refresh端点我希望能够将配置服务器 uri 切换到我刚刚收到的新的。

我查看了spring-cloud-config源代码,但那里的 bean 似乎没有用@RefreshScope.

springboot env/actuator/env似乎显示了收到的新 uri,但配置客户端 bean 似乎仍然指向引导 uri。

关于如何实现这一目标的任何建议?我对使用 springboot 相当陌生。

谢谢!

标签: javaspringspring-bootspring-cloud

解决方案


对于其他尝试这样做的人,我从初始启动中删除了 spring cloud 配置,并根据需要添加它,setConfigUri然后执行refreshObjects,这似乎从配置服务器获取配置。(不要忘记将 spring-cloud-config 和依赖项添加到 pom.xml 中)

这就是我所做的,到目前为止它似乎达到了目的。如果出现问题,请随时插话。

@Autowired
private ConfigurableEnvironment env;

@Autowired
private ConfigurableApplicationContext applicationContext;

@Autowired
private ContextRefresher refresher;

public void setConfigUri(String uri) throws Exception {
    MutablePropertySources propertySources = env.getPropertySources();
    Map<String, Object> map = new HashMap<>();
    map.put("spring.cloud.config.uri", uri);
    propertySources.addFirst(new MapPropertySource("defaultProperties", map));
    applicationContext.setEnvironment(env);
}

public void refreshObjects() throws Exception {
    refresher.refresh();
}

推荐阅读