1

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

MozenRath
  • 9,652
  • 13
  • 61
  • 104

1 Answers1

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 in deferredResult timeout set 10 sec. So after 10 sec you get Time Out. response... if you set sleep for less than 10 sec then you will get Task Finished response.

Look this for details.

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