eng*_*gma 17 java spring asynchronous
我正在尝试实现一个返回类型为Future的spring @Async任务,但我无法弄清楚如何正确地完成它.
编辑
从春季来源和春季参考手册:
甚至可以异步调用返回值的方法.但是,这些方法需要具有Future类型的返回值.这仍然提供了异步执行的好处,以便调用者可以在调用Future上的get()之前执行其他任务.
它给出了一个像这样的例子:
@Async
Future<String> returnSomething(int i) {
// this will be executed asynchronously
}
Run Code Online (Sandbox Code Playgroud)
如何正确实现?
Pet*_*lák 24
看看这篇博文.
使用@Async允许您以异步方式在方法中运行计算.这意味着如果它被调用(在Spring托管bean上),控件立即返回给调用者,方法中的代码在另一个线程中运行.调用者接收Future绑定到正在运行的计算的对象,并可以使用它来检查计算是否正在运行和/或等待结果.
创建这样的方法很简单.使用注释并将@Async结果包装AsyncResult,如博客文章所示.
看看这篇博文
重要配置是:
通过定义:在spring config xml中启用异步:
<!-- Enables the detection of @Async and @Scheduled annotations on any Spring-managed object. -->
<task:annotation-driven/>
Run Code Online (Sandbox Code Playgroud)
默认情况下将使用SimpleAsyncTaskExecutor.
将响应包装在Future <>对象中
例:
@Async
public Future<PublishAndReturnDocumentResult> generateDocument(FooBarBean bean) {
//do some logic
return new AsyncResult<PublishAndReturnDocumentResult>(result);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以检查结果是否已完成(result.isDone())或等待获取响应result.get()