3

Is there any way to refresh springboot configuration as soon as we change .properties file?

I came across spring-cloud-config and many articles/blogs suggested to use this for a distributed environment. I have many deployments of my springboot application but they are not related or dependent on one another. I also looked at few solutions where they suggested providing rest endpoints to refresh configs manually without restarting application. But I want to refresh configuration dynamically whenever I change .properties file without manual intervention.

Any guide/suggestion is much appreciated.

MLS
  • 617
  • 1
  • 7
  • 14

1 Answers1

4

Can you just use the Spring Cloud Config "Server" and have it signal to your Spring Cloud client that the properties file changed. See this example:

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

Under the covers, it is doing a poll of the underlying resource and then broadcasts it to your client:

    @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()));
        }
    }

If you don't want to use the config server, in your own code, you could use a similar scheduled annotation and monitor your properties file:

@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();
    } 
}
Dovmo
  • 8,121
  • 3
  • 30
  • 44
  • Is it efficient to use Scheduled in this case? I am trying to understand the overload[if there is any] to my application with this approach. I can't afford to restart the application to refresh config changes. But I want to keep it as efficient as possible by using available options to refresh on the fly. – MLS Aug 20 '18 at 23:36
  • 1
    The first option I suggested (using Spring Config Server) is probably your best approach then. It will basically send an event to your application. The downside, though, is that it's "inefficient" if you don't want to have that separate server running – Dovmo Aug 21 '18 at 02:14
  • Thanks @Dovmo. I will try first option and will see how it fits – MLS Aug 21 '18 at 02:51