3

Extending the question here:

Reading data from file at start to use in controller in Spring Boot

I want my spring boot application restart in production when the input file changes. I will start the app with something like this

java -jar application.jar [filename]

And when I modify the input text file, the app must be restarted and read the file again. How can I do it? I am asking how to watch file changes and trigger restart.

uploader33
  • 308
  • 1
  • 5
  • 16
  • Possible duplicate of [Programmatically restart Spring Boot application](http://stackoverflow.com/questions/29117308/programmatically-restart-spring-boot-application) – Nico Van Belle Apr 18 '17 at 12:46

1 Answers1

2

Solution using shell script

I will suggest to monitor your input file using file watchers, and if any file change detected, you can restart your app using shell scripts.

You didn't provided platform information.

If your production is on Linux then you can use watch to monitor changes in your input file.

Solution using Java

If you want to detect the file change in Java, you could use FileWatcher,

final Path path = FileSystems.getDefault().getPath(System.getProperty("user.home"), "Desktop");
System.out.println(path);
try{
    final WatchService watchService = FileSystems.getDefault().newWatchService();
    final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
    while (true) {
        final WatchKey wk = watchService.take();
        for (WatchEvent<?> event : wk.pollEvents()) {
            //we only register "ENTRY_MODIFY" so the context is always a Path.
            final Path changed = (Path) event.context();
            System.out.println(changed);
            if (changed.endsWith("myFile.txt")) {
                System.out.println("My file has changed");
            }
        }
        // reset the key
        boolean valid = wk.reset();
        if (!valid) {
            System.out.println("Key has been unregisterede");
        }
    }
}

Now to restart your app from within java, you have to start your application from within your main method.

Create a separate thread that will monitor your input file, and launch your app in a separate thread.

Whenever you detect any change in your input file, interrupt or kill the app thread, and re launch your application in a new thread.

Anil Agrawal
  • 2,748
  • 1
  • 24
  • 31