返回@Async方法导致Spring MVC和返回给Ajax客户 [英] Return @Async method result in Spring MVC and return it to Ajax client

查看:276
本文介绍了返回@Async方法导致Spring MVC和返回给Ajax客户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的控制器,它执行 @Async 工作

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

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

该方法的执行时间长达1O分钟。所有我需要做的仅仅是返回结果给客户端,这将使用AJAX / JQuery的连接。

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.

我不希望客户端请求我的服务器每秒 @Async 方法是否执行或者不执行。我只想让我的连接打开,然后就推结果到服务器。

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();
    }
}

我明白,这非常接近COMIT模式,但我不熟悉的彗星一般。

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

我的问题是我怎么能使用保持连接开放的客户端的JavaScript / JQuery的?

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

和将我的 @RequestMapping(值=/ async.do,方法= RequestMethod.POST)方法推结果给客户?

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

推荐答案

最简单的方法是不是要调用的方法以异步的方式,而不是直接从控制器的同步方式调用它。

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.

当然,这意味着,该连接将开放需要多长时间做这项工作(1分钟)。

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

这篇关于返回@Async方法导致Spring MVC和返回给Ajax客户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆