Spring MVC的异步请求DeferredResult

DeferredResult使用方式与Callable类似,但是在返回结果上触发不一样。DeferredResult它返回的时候实际结果可能没有生成,实际的结果可能会在另外的线程里面设置到DeferredResult中去。这个特性非常非常的重要,对后面实现复杂的功能,比如服务端推技术、订单过期时间处理、长轮询、模拟MQ的功能等等高级应用有着重要作用。

<code>@RequestMapping("/async/hello")
@ResponseBody
public DeferredResult<string> helloGet(){
DeferredResult<string> deferredResult = new DeferredResult<>();
//异步任务保存在队列中等待响应
deferredResultList.add(deferredResult);
//注意onCompletion表示任务完成回调,无论超时,错误都会执行,类似于finnally
deferredResult.onCompletion(new Runnable() {
@Override
public void run() {
System.out.println("complet async task");
}
});
//异步任务超时回调onTimeout
deferredResult.onTimeout(new Runnable() {
@Override
public void run() {
System.out.println("execute task timeout");
}
});
return deferredResult;
}

@RequestMapping("/async/hellotoall")
@ResponseBody
public void helloGetAll(){
deferredResultList.forEach(d -> d.setResult("say hello to all"));
}/<string>/<string>/<code>

1.我们第一个请求/async/hello,会先将异步任务deferredResult存在队列中,然后前端页面是一直等待(转圈状态)响应。

2.只到第二个请求:/async/Hellotoall 触发结果响应, 才会向客户端返回查询的结果。触发的方式多种多样。例如可以使用定时任务,也可以使用MQ消费方式去触发


分享到:


相關文章: