Spring 3.2 @Async任务,返回类型为Future

eng*_*gma 17 java spring asynchronous

我正在尝试实现一个返回类型为Future的spring @Async任务,但我无法弄清楚如何正确地完成它.

  1. 这样做我会得到什么?我现在能控制我的任务,所以我可以阻止并运行它吗?
  2. 有关如何做到这一点的参考实施吗?Springsource不提供任何.

编辑

从春季来源和春季参考手册:

甚至可以异步调用返回值的方法.但是,这些方法需要具有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,如博客文章所示.

  • @ Developer106是的,你可以通过调用[cancel(true)]来调度你的异步方法(http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html#cancel(boolean) ))返回的`Future`.但中断不会自动起作用.该方法应该通过调用`Thread.isInterrupted()`来检查中断,或者使用抛出`InterruptedException`的方法.请参阅The Java Tutorial中的[Interrupts](http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html). (3认同)

sha*_*lee 6

看看这篇博文

重要配置是:

  1. @async on spring managed bean方法
  2. 通过定义:在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()