开发者

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

开发者 https://www.devze.com 2023-04-11 12:41 出处:网络
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

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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号