如何在Web应用程序中实现请求超时?

时间:2016-05-19 10:24:25

标签: java spring-mvc spring-boot

我正在使用spring,如果请求在30Sec系统中没有响应,则应显示Request Time Out Page。

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
        FilterChain filterChain) throws IOException, ServletException {
    logger.info("method=doFilter, Executing TimeoutFilter");
    Timer timer = new Timer();

    timer.schedule(new TimerTask() {
        @Override
        public void run() {

            ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            try {
                logger.warn("method=doFilter, Request timed out");
                ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT, "Request Timed out");
                return;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return;
        }
    }, 30000);
    filterChain.doFilter(servletRequest, servletResponse);
    timer.cancel();
}

我的新TimerTask函数在30秒后被调用,但问题是请求仍然在我返回504状态后仍在运行。所以,我想返回504并结束该请求,请你为此建议一个解决方案

0 个答案:

没有答案