Timing out the execution time of a controller/method in Spring

送分小仙女□ 提交于 2019-12-21 03:58:22

问题


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.

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.

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.


回答1:


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

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).

Further reading:

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


来源:https://stackoverflow.com/questions/7663732/timing-out-the-execution-time-of-a-controller-method-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!