I have a Spring Boot application and what I want to achieve is that when my rest controllers take longer to process a request, then simply send an error without continuing to process the request. Is this possible? how do I achieve it in a way without modifying at the controller level but at the application level. This is on latest Spring boot 2.2.6.RELEASE
Asked
Active
Viewed 1,323 times
1

MozenRath
- 9,652
- 13
- 61
- 104
-
Webflux or MVC? – 123 May 12 '20 at 07:29
-
https://stackoverflow.com/questions/34852236/spring-boot-rest-api-request-timeout – Derrops May 13 '20 at 00:19
-
I am using mvc. so servlet – MozenRath May 13 '20 at 10:28
1 Answers
1
You can achieve it by using DeferredResult..
See this example:
@GetMapping("/test")
DeferredResult<String> test(){
Long timeOutInMilliSec = 10000L;
String timeOutResp = "Time Out.";
DeferredResult<String> deferredResult = new DeferredResult<>(timeOutInMilliSec,timeOutResp);
CompletableFuture.runAsync(()->{
try {
//Long pooling task;If task is not completed within 100 sec timeout response retrun for this request
TimeUnit.SECONDS.sleep(100);
//set result after completing task to return response to client
deferredResult.setResult("Task Finished");
}catch (Exception ex){
}
});
return deferredResult;
}
Here request sleep for
100
sec but indeferredResult
timeout set10
sec. So after 10 sec you getTime Out.
response... if you set sleep for less than 10 sec then you will getTask Finished
response.
Look this for details.

GolamMazid Sajib
- 8,698
- 6
- 21
- 39