Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting refreshing of RefreshScope beans

It is my understanding that when you use Spring Cloud's RefreshScope annotation, a Proxy to the data is injected, and the proxy is automatically updated if the backing information is changed. Unfortunately, I need to find a way to be alerted when that refresh occurs, so that my code can re-read the data from the refresh-scoped bean.

Simple example: A scheduled task whose schedule is stored in Cloud Config. Unless you wait until the next execution of the task (which could take a while) or regularly poll the configuration (which seems wasteful), there's no way to know if the configuration has changed.

like image 692
Cobra1117 Avatar asked Feb 10 '16 17:02

Cobra1117


Video Answer


2 Answers

EnvironmentChangeEvent is fired when there's a change in Environment. In terms of Spring Cloud Config it means it's triggered when /env actuator endpoint is called.

RefreshScopeRefreshedEvent is fired when refresh of @RefreshScope beans has been initiated, e.g. /refresh actuator endpoint is called.

That means that you need to register ApplicationListener<RefreshScopeRefreshedEvent> like that:

@Configuration
public class AppConfig {

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

}
like image 107
StasKolodyuk Avatar answered Oct 10 '22 02:10

StasKolodyuk


When the refresh occurs EnvironmentChangeEvent would be raised in your config client, as the documentation states:

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).

So, you can define your event listener for this event:

public class YourEventListener implements ApplicationListener<EnvironmentChangeEvent> {
    @Override
    public void onApplicationEvent(EnvironmentChangeEvent event) {
        // do stuff
    }
}
like image 42
Ali Dehghani Avatar answered Oct 10 '22 01:10

Ali Dehghani