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

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

廢話很少說直接上代碼app

/**
 * 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 配置ide

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

若是你有新的辦法,請賜教線程

相關文章
相關標籤/搜索