我正在尝试创建一个监视程序来查找对特定文件夹的更改。我已经创建了一个观察者并将它放在异步方法中,但是当我从服务调用它时,应用程序会由于观察者方法中的 while 循环而暂停。就好像该方法没有在新线程中执行。
这是包含我要执行的方法的类;
@Service
public class FileWatcher {
@Async
public Future<Object> watch(Path path, DataParser parser) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
path.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
File file = new File(path.toString() + "/" + event.context());
if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
parser.fileChanged(file);
}
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
parser.fileCreated(file);
}
if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
parser.fileRemoved(file);
}
}
key.reset();
}
return null;
}
}
然后,我在服务的构造函数中调用它。
@Service
public class SPIService {
private final String DATAFOLDER = "/spi";
private Path dataPath;
public SPIService(@Value("${com.zf.trw.visualisation.data.path}") String dataPath) {
this.dataPath = Paths.get(dataPath + DATAFOLDER);
FileWatcher fileWatcher = new FileWatcher();
try {
fileWatcher.watch(this.dataPath, new SPIParser());
} catch (Exception e) {
e.printStackTrace();
}
}
}
为什么这不起作用?是因为我从服务的构造函数中调用方法吗?
最佳答案
您正在使用 new FileWatcher()
,这意味着该实例不是托管 bean。这也意味着 @Async
被忽略(这解释了您的应用程序暂停)。你需要 @Autowire
FileWatcher
来代替。
另请注意,您的解决方案对我来说似乎非常可疑,不仅因为有一个无限循环,而且在 @Async
方法中有一个(这会产生一些重要的后果)。我至少会为此使用一个单线程线程池。
关于java - 异步方法中的 Spring Boot while 循环停止应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51931868/