aldrael
aldrael

Reputation: 567

How to invoke async controller logic after returning response using Spring?

I need to process request asynchronously in time - after receiving request I must return a response with status 200 to confirm that the request have reached it's goal, and then proceed with some magic to happen in service. I tried few ways to reach it, but every time response was sent after logic part ended in some other thread.

Is there a way to reach it using Spring? Or should I rather think about other approach to this problem?

Upvotes: 4

Views: 1755

Answers (2)

paul
paul

Reputation: 13471

You need to use deferredResult http://docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/web/context/request/async/DeferredResult.html

You will create a deferredResult object and you will return to the client. then asynchronously you will execute the logic and as soon as you finish you will inform the client that the request it´s done. This technique is also know as "http long polling"

    @RequestMapping("/")
   @ResponseBody
   public DeferredResult<String> square() throws JMSException {

       final DeferredResult<String> deferredResult = new DeferredResult<>();
       runInOtherThread(deferredResult);
       return deferredResult;
   }


   private void runInOtherThread(DeferredResult<String> deferredResult) {
       //seconds later in other thread...
       deferredResult.setResult("HTTP response is: 42");
   }

Upvotes: 0

khanou
khanou

Reputation: 1454

The Spring Framework provides abstractions for asynchronous execution and scheduling of tasks

You can look at this => http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html

Upvotes: 2

Related Questions