简体   繁体   English

如何使用 Spring AsyncResult 和 Future Return

[英]How to use Spring AsyncResult and Future Return

I have a public interface, Synchronous, that gets exposed to several service layer classes.我有一个公共接口 Synchronous,它暴露给多个服务层类。 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.它的目的是根据传递的 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.我正在尝试使用 Spring AsyncResult,但我不确定返回的对象 WorkResult 实际返回到什么。 Do I need to put a handler somewhere in the SynchronousImpl?我需要在 SynchronousImpl 的某个地方放置一个处理程序吗? Ideas?想法?

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);
    }
}

A Future has nothing to do with Spring, Future are classes that belong to the Java 6 concurrency framework. Future与 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 @Async annotation) the caller gets immediately the Future Object.在 async 方法启动后(这是 Spring 帮助其@Async注释的地方),调用者立即获得Future对象。 But the future object is not the result, it is just a wrapper/placeholder/proxy/reference for the real result.但是未来的对象不是结果,它只是真实结果的包装器/占位符/代理/引用。

Now the caller and the worker run in parallel and can do different things.现在调用者和工作者并行运行并且可以做不同的事情。 When the caller invokes futureResult.get();当调用者调用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();并且已经计算出真正的结果时,他立即得到结果)

@Aysnc
public Future doWork() {
   if (reason) {
      return; // Missing return value error,,but i needn't return anything
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM