检测 RefreshScope bean 的刷新

Detecting refreshing of RefreshScope beans

据我了解,当您使用 Spring Cloud 的 RefreshScope 注释时,会注入数据代理,如果支持信息发生更改,代理会自动更新。不幸的是,我需要找到一种在刷新发生时收到警报的方法,以便我的代码可以从刷新范围的 bean 中重新读取数据。

简单示例:计划任务的计划存储在Cloud Config 中。除非你等到任务的下一次执行(这可能需要一段时间)或定期轮询配置(这看起来很浪费),否则无法知道配置是否已更改。

当刷新发生时 EnvironmentChangeEvent 将在您的配置客户端中引发,如文档所述:

The application will listen for an EnvironmentChangedEvent and react to the change in a couple of standard ways (additional ApplicationListeners can be added as @Beans by the user in the normal way).

因此,您可以为此事件定义事件侦听器:

public class YourEventListener implements ApplicationListener<EnvironmentChangeEvent> {
    @Override
    public void onApplicationEvent(EnvironmentChangeEvent event) {
        // do stuff
    }
}

我认为一种方法是用 @RefreshScope 注释所有具有配置外化属性并在 @Value ( "${your.prop.key}" ) 注释中注释的 bean。

这些属性在配置更改时更新。

EnvironmentChangeEventEnvironment 发生变化时触发。就 Spring Cloud Config 而言,这意味着它在调用 /env 执行器端点时触发。

RefreshScopeRefreshedEvent@RefreshScope bean 的刷新启动时触发,例如/refresh 执行器端点被调用。

这意味着你需要这样注册ApplicationListener<RefreshScopeRefreshedEvent>:

@Configuration
public class AppConfig {

    @EventListener(RefreshScopeRefreshedEvent.class)
    public void onRefresh(RefreshScopeRefreshedEvent event) {
        // Your code goes here...
    }

}

更具体地说,在刷新范围 RefreshScope 下的属性和应用程序上下文后,触发事件 RefreshScopeRefreshedEvent。鉴于属性已完成更新(您可以确保只捕获更新的值),您可以为此设置一个侦听器。