超时控制器/方法的执行时间春季 [英] Timing out the execution time of a controller/method in Spring

查看:182
本文介绍了超时控制器/方法的执行时间春季的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有当前正在正常访问一个Spring控制器,但我想改变以这样的方式,如果所述控制器执行的任务时间超过例如10秒的规定时间更那么控制器可以与响应的执行一个您的请求正在处理消息给调用者,但如果方法时,那么响应传递给从控制器调用的方法中返回,换句话说,我想从一个Spring控制器定时异步执行。

I have a Spring controller that is currently being accessed normally, but i want to change the implementation in such a way that if the task the controller is performing takes more than a defined time for instance 10 seconds then the controller can respond with a "your request is being processed message" to the caller, but if the method returns within time then the response is passed to the calling method from the controller, in other words i want timed asynchronous execution from a Spring controller.

注意:这是不完全(至少根据我的理解),因为我不希望只是交出执行到的TaskExecutor并立即返回TaskExecutor的域。

NB: This is not exactly TaskExecutor domain(at least according to my understanding) because i don't want to just hand over execution to the TaskExecutor and return immediately.

我使用Spring 3.0和Java 1.5和控制器没有意见,我只想写输出定向到流,它调用客户的期望。

I use Spring 3.0 and Java 1.5 and the controllers don't have views, i just want to write the output direct to stream, which the calling client expects.

推荐答案

那么,它的的TaskExecutor 域。在你的控制器则只需将您的处理逻辑可赎回,将其提交给 AsyncTaskExecutor 并等待10秒钟。这就是它!

Well, it is the TaskExecutor domain. In your controller simply wrap your processing logic in Callable, submit it to the AsyncTaskExecutor and wait up to 10 seconds. That's it!

final Future<ModelAndView> future = asyncTaskExecutor.submit(new Callable<ModelAndView>() {
    @Override
    public ModelAndView call() throws Exception {
        //lengthy computations...
        return new ModelAndView("done");
    }
});
try {
    return future.get(10, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    return new ModelAndView("timeout");
}

当然,这是一个有点讨厌的,特别是当它发生时比一个控制器一次。如果是这种情况,你应该看看servlet的3.0异步支持(见下文)。

Of course this is a bit nasty, especially when it occurs more than once in one controller. If this is the case, you should have a look at servlet 3.0 asynchronous support (see below).

  • 25. Task Execution and Scheduling
  • How to use Servlet 3 @WebServlet & async with Spring MVC 3?
  • Support Servlet 3.0 (JSR-315)

这篇关于超时控制器/方法的执行时间春季的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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