java - 返回类型为 Future 的 Spring 3.2 @Async 任务

标签 java spring asynchronous

我正在尝试实现一个返回类型为 Future 的 spring @Async 任务, 但我真的不知道如何正确地做到这一点。

  1. 这样做我会得到什么?我现在可以控制我的任务,以便我可以停止并运行它吗?
  2. 有没有关于我如何做到这一点的引用实现? 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/

相关文章:

javascript - 从 API 中提取文件并通过管道传输它会导致在我尝试读取它时出现文件未找到错误

java - Java POJO 上的 groupBy 的 Spark 数据集错误

java - Spring-RMI 事件导致 java.io.InvalidClassException : filter status: REJECTED

java - Spring 3 MVC 请求验证

javascript - 如何使用 setTimeout 和 Promise 使这段 JS 代码更实用?

javascript - JS : Conventional structure for defining a callback function?

java - 使用GSON解析JSON得到 "content"

java - 新创建的heroku应用程序没有网络测功机

java - 使用 Java 通过暴力计算多项式

spring security - 为什么不在登录表单中使用 'spring-security-redirect' 参数重定向到特定页面