我正在尝试实现一个返回类型为 Future 的 spring @Async 任务, 但我真的不知道如何正确地做到这一点。
- 这样做我会得到什么?我现在可以控制我的任务,以便我可以停止并运行它吗?
- 有没有关于我如何做到这一点的引用实现? springsource 不提供。
编辑
来自 Spring 源和 Spring 引用手册:
Even methods that return a value can be invoked asynchronously. However, such methods are required to have a Future typed return value. This still provides the benefit of asynchronous execution so that the caller can perform other tasks prior to calling get() on that Future.
它给出了一个这样的例子:
@Async
Future<String> returnSomething(int i) {
// this will be executed asynchronously
}
如何正确实现?
最佳答案
查看 this blog post .
使用 @Async
允许您在方法中异步运行计算。这意味着如果它被调用(在 Spring 托管 bean 上),控制将立即返回给调用者,并且方法中的代码在另一个线程中运行。调用者接收到一个绑定(bind)到正在运行的计算的 Future
对象,并可以使用它来检查计算是否正在运行和/或等待结果。
创建这样的方法很简单。使用 @Async
对其进行注解,并将结果包装在 AsyncResult
中,如博文所示。
关于java - 返回类型为 Future 的 Spring 3.2 @Async 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17249989/