For long polling requests, you can use DeferredResult
. When you return a DeferredResult
response, the request thread will be free and the request will be handled by a worker thread. Here is one example:
@GetMapping("/test")
DeferredResult<String> test(){
long timeOutInMilliSec = 100000L;
String timeOutResp = "Time Out.";
DeferredResult<String> deferredResult = new DeferredResult<>(timeOutInMilliSec, timeOutResp);
CompletableFuture.runAsync(()->{
try {
//Long polling task; if task is not completed within 100s, timeout response returned for this request
TimeUnit.SECONDS.sleep(10);
//set result after completing task to return response to client
deferredResult.setResult("Task Finished");
}catch (Exception ex){
}
});
return deferredResult;
}
This request demonstrates providing a response after waiting 10s. If you set sleep(100)
or longer, you will get a timeout response.
Check this out for more options.