嗨,我应该如何防止 http 请求超时?
非常感谢
最佳答案
您想防止网络浏览器在长时间运行的 HTTP 请求中超时?
您需要在响应中写入一些内容,即使它只是进度的简单可视化。或者在后台线程而不是 HTTP 请求线程中执行长时间运行的任务。或者优化长时间运行的任务,使其不会运行得太长。
<小时/>更新:根据评论,您可以在 ExecutorService
的帮助下创建后台线程。并将长时间运行的任务提交给它。
public class LongRunningTaskServlet extends HttpServlet {
private ExecutorService executor;
@Override
public void init() {
executor = Executors.newSingleThreadExecutor();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
// First gather necessary parameters for the background task (you shouldn't pass request/response to it!).
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");
// Then create the background task and submit it to the executor.
executors.submit(new LongRunningTask(param1, param2));
// It returns a Future, you can if necessary store it in session so that you can later check if it is finished and/or has returned a result.
// Immediately display result.
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);
}
@Override
public void destroy() {
executor.shutdownNow(); // Important! Pevent thread leaking.
}
}
LongRunningTask
类必须实现 Callable<T>
或 Runnable
。小心线程,不要删除 destroy()
在上面的例子中。
另请参阅:
关于java - JSP如何防止HTTP请求超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5521461/