Spring中控制器/方法的执行时间超时

发布于 2024-12-08 11:30:49 字数 302 浏览 1 评论 0原文

我有一个当前正在正常访问的 Spring 控制器,但我想以这样的方式更改实现:如果控制器正在执行的任务花费的时间超过定义的时间(例如 10 秒),则控制器可以响应“您的请求正在处理消息”给调用者,但如果该方法在时间内返回,则响应将从控制器传递给调用方法,换句话说,我希望从 Spring 控制器定时异步执行。

注意:这不完全是 TaskExecutor 域(至少根据我的理解),因为我不想将执行移交给 TaskExecutor 并立即返回。

我使用 Spring 3.0 和 Java 1.5,控制器没有视图,我只想将输出直接写入流,这是调用客户端所期望的。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温柔一刀 2024-12-15 11:30:49

嗯,它 TaskExecutor 域。在您的控制器中,只需将处理逻辑包装在 Callable 中,将其提交给 AsyncTaskExecutor 并等待最多 10 秒。就是这样!

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 异步支持(见下文)。

进一步阅读:

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:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文