利用springMVC的interceptor实现页面性能监控(Filter亦可)

   调优第一步,找出耗时比较长的页面进行优化。利用interceptor能轻易搞定。interceptor提供了preHandle和postHandle以及afterCompletion三个方法。preHandle调用controller具体方法之前调用,postHandle完成具体方法之后调用,afterCompletion完成对页面的render以后调用,至此整个页面渲染完成。也就是说我们在preHandle记录开始的时间,在afterCompletion记录结束的时间,就可或者整个页面生成的时间。Spring自带StopWatch工具类来实现时间跟踪,关键一点interceptor不是线程安全的。我们需要借助threadlocal来实现线程安全。

@Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        if(usePerformance){
        	StopWatch stopWatch = new StopWatch(handler.toString());
            stopWatchLocal.set(stopWatch);
            stopWatch.start(handler.toString());
        }
        
        return true;
    }


 @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    	if(usePerformance){
    		StopWatch stopWatch = stopWatchLocal.get();
            stopWatch.stop();
            String currentPath = request.getRequestURI();
            String queryString  = request.getQueryString();
            queryString = queryString == null ? "":"?" + queryString;
            log.info("access url path:" + currentPath + queryString +  " |time:" + stopWatch.getTotalTimeMillis());
            stopWatchLocal.set(null);
    	}
        
    }

呵呵,如果你没有使用springMVC可以使用filter来完成

stopWatch.start();

doFilterChain();
stopWatch.stop();

相关推荐