Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return @Async method result in Spring MVC and return it to Ajax client

I Have some method inside my Controller which executes @Async task

@Async
public Future<String> getResultFromServer(){
    String result = ......
    return new AsyncResult<String>(result);
} 

The method execution time is up to 1o minutes. All I need to do is just to return result to client side which will be connected using AJAX/JQuery.

I don't want the client to request my server every second whether @Async method executed or not. I just want to keep my connection open and then just "push" result to Server.

@RequestMapping(value="/async.do", method=RequestMethod.POST)
public void getResult(HttpServletResponse res){
    String result = null;
    PrintWriter out = res.getWriter();
    Future<String> future = getResultFromServer();
    try {
        if (future.isDone())
            result = future.get();
        out.println(result);
        out.close();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
}

I understand that this very close to Comit model, but I'm not familiar with comet in general.

My question is how can I keep connection open on client side using JavaScript/JQuery?

and will my @RequestMapping(value="/async.do", method=RequestMethod.POST) method push result to the client?

like image 568
danny.lesnik Avatar asked Oct 26 '11 18:10

danny.lesnik


1 Answers

The easiest way would be not to invoke the method in a asynchronous way, instead invoke it directly from the controller in a synchronous way.

Then the request will need to "wait" until the method result is calculated, and it can be returned as soon as it is created.

Of course this means, that the connection will be open for how long it takes do the job (1 minute).

like image 123
Ralph Avatar answered Sep 28 '22 20:09

Ralph