Java 如何使用 Spring AsyncResult 和 Future Return

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21313831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:59:46  来源:igfitidea点击:

How to use Spring AsyncResult and Future Return

javaspringasynchronous

提问by c12

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.

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

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?

我正在尝试使用 Spring AsyncResult,但我不确定返回的对象 WorkResult 实际返回到什么。我需要在 SynchronousImpl 的某个地方放置一个处理程序吗?想法?

Sync Public Service:

同步公共服务:

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

Async Worker Class:

异步工作者类:

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

采纳答案by Ralph

A Futurehas nothing to do with Spring, Futureare classes that belong to the Java 6 concurrency framework.

AFuture与 Spring 无关,Future是属于 Java 6 并发框架的类。

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.
}

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

在异步方法启动后(这是 Spring 帮助其@Async注释的地方),调用者立即获得Future对象。但是未来的对象不是结果,它只是真实结果的包装器/占位符/代理/引用。

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)

现在调用者和工作者并行运行并且可以做不同的事情。当调用者调用futureResult.get();并且尚未计算实际结果时,该线程将被阻塞,直到工作人员提供结果为止。(当调用者调用futureResult.get();并且已经计算出真正的结果时,他立即得到结果)