gpt4 book ai didi

spring - 在 Spring 中超时 Controller /方法的执行时间

转载 作者:IT老高 更新时间:2023-10-28 13:50:36 27 4
gpt4 key购买 nike

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

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

我使用 Spring 3.0 和 Java 1.5,并且 Controller 没有 View ,我只想将输出直接写入流,这是调用客户端所期望的。

最佳答案

嗯,它 TaskExecutor 域。在您的 Controller 中,只需将处理逻辑包装在 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");
}

当然,这有点令人讨厌,尤其是当它在一个 Controller 中多次发生时。如果是这种情况,您应该看看 servlet 3.0 异步支持(见下文)。

延伸阅读:

关于spring - 在 Spring 中超时 Controller /方法的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7663732/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com