gpt4 book ai didi

java - 输入文本文件更改时重新启动 Spring Boot

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:11:48 25 4
gpt4 key购买 nike

在这里扩展问题:

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

我希望我的 spring boot 应用程序在输入文件更改时重新启动生产。我将用这样的东西启动应用程序

java -jar application.jar [filename]

而且当我修改输入文本文件时,应用程序必须重新启动并再次读取文件。我该怎么做?我问的是如何查看文件更改并触发重启。

最佳答案

使用shell脚本解决

我会建议使用文件观察器监控您的输入文件,如果检测到任何文件更改,您可以使用 shell 脚本重新启动您的应用程序。

您没有提供平台信息。

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

使用 Java 的解决方案

如果你想在 Java 中检测文件变化,你可以使用 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");
}
}
}

现在要从 java 中重新启动您的应用程序,您必须从您的 main 方法中启动您的应用程序。

创建一个单独的线程来监控您的输入文件,并在一个单独的线程中启动您的应用。

每当您检测到输入文件有任何变化时,中断或终止应用程序线程,并在新线程中重新启动您的应用程序。

关于java - 输入文本文件更改时重新启动 Spring Boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43472459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com