Search code examples
javaspringspring-bootspring-restcontroller

only heat a URI, not wait for responce in Spring Rest


Suppose I click on URI localhost:8080/admin/hello with Hello class POST JSON object using POSTMAN and have a Controller like,

@RequestMapping(value = "/hello", method = RequestMethod.POST)
public ResponseEntity<Hello> helloHome(@RequestBody Hello obj){
//here it goes to service class and doing processes...
return new ResponseEntity<Hello>(obj, HttpStatus.OK);
}

I only want the URI to hit the Controller but not wait for response (because processing all the service class process takes 10 seconds but I want to return immediate without response).

How can I implement it?


Solution

  • You can enable Async processing by enabling it via your config.

    @Configuration
    @EnableAsync
    public class YourConfig
    

    Now you can add a service and enable async processing on one of its methods by annotating it with @Async. It will return immediately after it was called.

    @Async
    public void asyncMethodOnAService() {}
    

    If you want to service to return a value you can return a CompletableFuture

    @Async
    public CompletableFuture<String> asyncMethodOnAService() {}
    

    The controller that call the async method can return a DeferredResult which will let the client know that the result will be available once the async processing has finished.

        @RequestMapping(value = "/async", method = RequestMethod.GET)
        public DeferredResult<ResponseEntity<String>> doAsync() {
    
          DeferredResult<ResponseEntity<String>> result = new DeferredResult<>();
          this.asyncService.asyncMethodOnAService().whenComplete((serviceResult, throwable) -> result.setResult(ResponseEntity.ok(serviceResult)));
    
          return result;
        }