簡體   English   中英

在Async方法中循環的Spring Boot會暫停應用程序

[英]Spring Boot while loop in Async method halts application

我正在嘗試創建一個查找特定文件夾更改的觀察程序。 我已經創建了一個觀察程序,並將其置於Async方法中,但是當我從服務中調用它時,應用程序暫停,因為觀察者方法中的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方法中有一個(這會產生一些重要的后果)。 我至少會使用單線程線程池。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM