使用Filter计算请求耗时

使用Filter计算请求耗时

有时为了更详细的检测web系统性能,需要计算每次请求到响应所耗费的时间,然后看看哪些请求耗时较多,从而有针对性的进行优化操作,此时可以使用Filter过滤器自己实现一个请求响应耗时计算的功能。每个请求在到达目标资源之前都会被Filter过滤器拦截,我们可以在请求到达之前获取系统当前的时间,每个响应也会先被Filter过滤器拦截,我们在此时也获取一下系统的当前时间,之后将两次时间作比较就能计算出这次请求响应所耗费的时间了。

创建一个Filter过滤器

package com.monkey1024.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalTime;

@WebFilter(filterName = "TimeFilter",urlPatterns = "/*")
public class TimeFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;

        //请求时的系统时间
        LocalTime time1 = LocalTime.now();


        chain.doFilter(req, resp);

        //响应时的系统时间
        LocalTime time2 = LocalTime.now();
        //计算请求响应耗时
        Duration total = Duration.between(time1, time2);
        System.out.println(request.getRequestURI() + "耗时:" + total.toMillis());
    }

    public void init(FilterConfig config) throws ServletException {

    }

}

通过上面的Filter过滤器就可以计算每次请求响应的耗时了,并且还可以查看到请求的目标资源,从而有针对性的做优化处理。

创建一个用于测试的Servlet:

package com.monkey1024.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "TestServlet",urlPatterns = {"/test"})
public class TestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //为了查看效果,所以睡眠3秒
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}