如何使用Spring AsyncResult和Future Return [英] How to use Spring AsyncResult and Future Return

查看:106
本文介绍了如何使用Spring AsyncResult和Future Return的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个公共接口Synchronous,该接口公开给几个服务层类.其目的是根据传递的id查找对象图,执行一些业务逻辑,然后将其传递给Spring Asynchronous方法Asynchronous.doWork以完成其余任务.

I have a public interface, Synchronous, that gets exposed to several service layer classes. Its intent is to lookup an object graph based on the id being passed, do some business logic and then pass it on to the Spring Asynchronous method Asynchronous.doWork to finish the rest of the task.

我正在尝试使用Spring AsyncResult,但是我不确定返回的对象WorkResult实际返回的内容.我是否需要在SynchronousImpl中的某个地方放置处理程序?有想法吗?

I'm trying to use the Spring AsyncResult but I'm unsure what the returned object WorkResult actually gets returned to. Do I need to put a handler somewhere in the SynchronousImpl? Ideas?

同步公共服务:

public class SynchronousImpl implements Synchronous {
    private Asynchronous async;
    //business logic
    public void doWork(long id){
        async.doWork(id);
    }
}

异步工作者类:

public class Asynchronous {
    @Async
    public Future<WorkResult> doWork(long id){
        //business logic
        WorkResult result = new WorkResult(id, "Finished");
        return new AsyncResult<WorkResult>(result);
    }
}

推荐答案

A

A Future has nothing to do with Spring, Future are classes that belong to the Java 6 concurrency framework.

一个典型的用例是这样的:

A typical use case is this:

public void doWork(long id) {
    Future<WorkResult> futureResult = async.doWork(id);
    //Do other things.
    WorkResult result = futureResult.get(); //The invocation will block until the result is calculated.
}

启动异步方法后(Spring在其中提供 @Async 批注的帮助),调用方立即获得 Future 对象.但是将来的对象不是结果,它只是实际结果的包装器/占位符/代理/引用.

After the async method is started (that is where Spring helps with its @Async annotation) the caller gets immediately the Future Object. But the future object is not the result, it is just a wrapper/placeholder/proxy/reference for the real result.

现在,调用方和工作进程并行运行,并且可以执行不同的操作.当调用方调用 futureResult.get(); 且尚未计算实际结果时,此线程将被阻塞,直到工作人员提供结果为止.(当调用方调用 futureResult.get(); 并且已经计算出实际结果时,他会立即获得结果)

Now the caller and the worker run in parallel and can do different things. When the caller invokes futureResult.get(); and the real result is not calculated yet, this thread gets blocked until the result is provided by the worker. (When the caller invokes futureResult.get(); and the real result is already calculated, he gets the result immediately)

这篇关于如何使用Spring AsyncResult和Future Return的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆