How to make Java rest api call return not wait immediately?

@RequestMapping(value = "/endpoint", method = RequestMethod.POST) public ResponseEntity<?> endpoint(@RequestBody final ObjectNode data, final HttpServletRequest request) { somefunction(); return new ResponseEntity<>(HttpStatus.OK); } public somefunction() { ..... } 

In the Java spring controller, I have an endpoint. When this endpoint is called, I want it to return directly, rather than waiting for somefunction() to complete. Can anyone teach me how to deal with this?

+5
source share
3 answers

If you are using Java 8, you can use the new Executor classes:

 @RequestMapping(value = "/endpoint", method = RequestMethod.POST) public ResponseEntity<?> endpoint(@RequestBody final ObjectNode data, final HttpServletRequest request) { Executors.newScheduledThreadPool(1).schedule( () -> somefunction(), 10, TimeUnit.SECONDS ); return new ResponseEntity<>(HttpStatus.ACCEPTED); } 

It will be:

  • Schedule somefunction() to run after a 10 second delay.
  • HTTP 202 Return Accepted (this is what you should return when the POST endpoint actually creates nothing in place).
  • Run somefunction() after 10 seconds.
+5
source

change line

 somefunction(); 

be

 new Thread() { public void run() { somefunction(); } }.start(); 
+2
source

You should use RxJava , which offers you promises. You will have a DefferedResult that will be returned asynchronously, so it will not block the execution of other methods.

For instance:

 @RequestMapping("/getAMessageFutureAsync") public DeferredResult<Message> getAMessageFutureAsync() { DeferredResult<Message> deffered = new DeferredResult<>(90000); CompletableFuture<Message> f = this.service1.getAMessageFuture(); f.whenComplete((res, ex) -> { if (ex != null) { deffered.setErrorResult(ex); } else { deffered.setResult(res); } }); return deffered; } 

- Source code and tutorial

+1
source

Source: https://habr.com/ru/post/1260631/


All Articles