1. 程式人生 > >spring mvc攔截器,實現統計http請求的後臺執行時間

spring mvc攔截器,實現統計http請求的後臺執行時間

使用兩種方式,實現攔截http請求的後臺執行時間。

廢話不多說直接上程式碼

/**
 * Http請求時間統計
 * 攔截所有請求
 */
public class HttpRquestTimeInterceptor extends HandlerInterceptorAdapter {

    ThreadLocal<Long> localThread = new ThreadLocal<Long>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //執行緒方式
        localThread.set(System.currentTimeMillis());
        //request方式
        request.setAttribute("_startTime", System.currentTimeMillis());

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        Long endTime = System.currentTimeMillis();


        System.out.println(request.getServletPath() + " >> http請求結束執行緒:" + (endTime - localThread.get()));



        Long startTime = (Long)request.getAttribute("_startTime");

        System.out.println(request.getServletPath() + " >> http請求結束:" + (endTime - startTime));

    }
}

Spring 配置

<mvc:interceptors>
		<!-- Http請求統計 -->
		<mvc:interceptor>
			<mvc:mapping path="/**" />
			<bean class="HttpRquestTimeInterceptor" ></bean>
		</mvc:interceptor>
	</mvc:interceptors>

如果你有新的辦法,請賜教