异步方法中的 Spring Boot while 循环停止应用程序

我正在尝试创建一个观察者来查找对特定文件夹的更改。我创建了一个观察者并将它放在一个异步方法中,但是当我从服务中调用它时,应用程序由于观察者方法中的 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();

        }

    }


}

为什么这不起作用?是因为我从服务的构造函数中调用方法吗?



HUX布斯
浏览 326回答 1
1回答

斯蒂芬大帝

您正在使用new FileWatcher()这意味着该实例不是托管 bean。这也意味着@Async被忽略(这解释了您的应用程序停止)。你需要@Autowire&nbsp;FileWatcher改为。另请注意,您的解决方案对我来说似乎非常可疑,不仅因为有无限循环,而且在@Async方法中有一个(这有一些重要的后果)。我至少会为它使用一个单线程线程池。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java