动态刷新springboot配置

问题描述 投票:0回答:2

有没有办法在我们更改

springboot
文件后立即刷新
.properties
配置?

我遇到了

spring-cloud-config
,许多文章/博客建议将其用于分布式环境。我的
springboot
应用程序有很多部署,但它们彼此不相关或不依赖。我还研究了一些解决方案,他们建议提供休息端点来手动刷新配置,而无需重新启动应用程序。但我想每当更改
.properties
文件时动态刷新配置,而无需手动干预。

非常感谢任何指导/建议。

spring-boot spring-cloud spring-cloud-config spring-config
2个回答
4
投票

您可以只使用 Spring Cloud 配置“服务器”并向您的 Spring Cloud 客户端发出属性文件已更改的信号吗?看这个例子:

https://spring.io/guides/gs/centralized-configuration/

在幕后,它正在对底层资源进行轮询,然后将其广播给您的客户端:

    @Scheduled(fixedRateString = "${spring.cloud.config.server.monitor.fixedDelay:5000}")
    public void poll() {
        for (File file : filesFromEvents()) {
            this.endpoint.notifyByPath(new HttpHeaders(), Collections
                    .<String, Object>singletonMap("path", file.getAbsolutePath()));
        }
    }

如果您不想使用配置服务器,在您自己的代码中,您可以使用类似的预定注释并监视您的

properties
文件:

@Component
public class MyRefresher {

    @Autowired
    private ContextRefresher contextRefresher;

    @Scheduled(fixedDelay=5000)
    public void myRefresher() {
        // Code here could potentially look at the properties file 
        // to see if it changed, and conditionally call the next line...
        contextRefresher.refresh();
    } 
}

0
投票

调用此函数来重新加载

@RefreshScope
beans

ctx.getBean(RefreshScope.class).refreshAll();

© www.soinside.com 2019 - 2024. All rights reserved.