DeferredResult常用来实现客户端长轮询,可以将异步处理的结果在特定时间内(如果设置了超时时间)返回给客户端。
java
@Slf4j
@RestController
@RequestMapping("/demo")
public class DemoDeferredResult {
@GetMapping("/deferredResult")
public DeferredResult<ApiResponse<String>> getDeferredResult(@RequestParam String param) {
DeferredResult<ApiResponse<String>> deferredResult = new DeferredResult<>();
deferredResult.onCompletion(() -> log.info("onCompletion"));
deferredResult.onTimeout(() -> log.info("onTimeout"));
new Thread(() -> {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
log.error("InterruptedException", e);
}
deferredResult.setResult(ApiResponse.success(param + UUID.randomUUID()));
}).start();
return deferredResult;
}
}
流程:
1.请求发送到服务端
2.处理器处理controller方法,返回DeferredResult
3.返回值处理器根据DeferredResult调用 selectHandler 选择对应的处理器DeferredResultMethodReturnValueHandler
4.handleReturnValue方法里面通过WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(result, mavContainer) 处理异步请求
5.设置addTimeoutHandler,addErrorHandler,addCompletionHandler,setResultHandler等处理器,最关键的是setResultHandler,后续在deferredResult.setResult时会调用
6.异步结果处理完之后,也就是业务代码调用deferredResult.setResult时会执行resultHandler逻辑
7.最终会执行this.asyncWebRequest.dispatch();分发请求,返回给客户端