gpt4 book ai didi

java - Spring 中长期运行的服务?

转载 作者:行者123 更新时间:2023-11-30 06:21:22 26 4
gpt4 key购买 nike

我想在我的 Spring 应用程序中使用 Java 7 WatchService 监视目录更改的服务。这个想法是,当目录中的文件发生更改时,通过 WebSockets 连接的客户端会收到通知。

如何让一个 bean 作为服务在它自己的线程中运行?

最佳答案

您要找的是Asynchronous execution.使用正确配置的上下文(请参阅链接),您可以像这样声明一个类

@Component
public class AsyncWatchServiceExecutor {
@Autowired
private WatchService watchService; // or create a new one here instead of injecting one

@Async
public void someAsyncMethod() {
for (;;) {
// use WatchService
}
}
}

您在 someAsyncMethod() 中所做的一切都将在单独的线程中发生。您所要做的就是调用一次。

ApplicationContext context = ...; // get ApplicationContext
context.getBean(AsyncWatchServiceExecutor.class).someAsyncMethod();

按照 Oracle documentation 中的说明使用 WatchService .


如果您不能直接访问您的 ApplicationContext,您可以将该 bean 注入(inject)到其他 bean 中并在 @PostConstruct 方法中调用它。

@Component
public class AsyncInitializer {
@Autowired
private AsyncWatchServiceExecutor exec;

@PostConstruct
public void init() {
exec.someAsyncMethod();
}
}

请注意您使用的代理策略(JDK 或 CGLIB)。

关于java - Spring 中长期运行的服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20619961/

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