SpringMVC拦截器实践与原理分析

使用场景:

统计请求耗时

使用姿势:

public class LogInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("ThreadLocal StartTime");

    private static Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
              Object handler) throws Exception {
        if (logger.isDebugEnabled()) {
            long beginTime = System.currentTimeMillis();//1、开始时间    
            startTimeThreadLocal.set(beginTime);        //线程绑定变量(该数据只有当前请求的线程可见)    
            logger.debug("开始计时: {}  URI: {}", new SimpleDateFormat("hh:mm:ss.SSS")
                    .format(beginTime), request.getRequestURI());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
               ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {
            logger.info("ViewName: " + modelAndView.getViewName());
        }
    }

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

        // 保存日志  
//        LogUtils.saveLog(request, handler, ex, null);

        // 打印JVM信息。  
        if (logger.isDebugEnabled()) {
            long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量(开始时间)    
            long endTime = System.currentTimeMillis();  //2、结束时间    
            logger.debug("计时结束:{}  耗时:{}s  URI: {}  最大内存: {}m  已分配内存: {}m  已分配内存中的剩余空间: {}m  最大可用内存: {}m",
                    new SimpleDateFormat("hh:mm:ss.SSS").format(endTime),
                    (endTime - beginTime)/1000,
                    request.getRequestURI(), Runtime.getRuntime().maxMemory() / 1024 / 1024,
                    Runtime.getRuntime().totalMemory() / 1024 / 1024, Runtime.getRuntime().freeMemory() / 1024 / 1024,
                    (Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory()) / 1024 / 1024);
        }
    }
}

 在springmvc配置文件里配置拦截器:

<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/**"/>
		<bean class="全限定名.LogInterceptor"/>
	</mvc:interceptor>
</mvc:interceptors>

原理分析:

1、类继承关系

2、数据结构(属性和方法)

 

总结:

 

参考:

https://gitbook.cn/books/5aa76072a2ac4c0459d661ee/index.html

https://gitbook.cn/gitchat/activity/5ac873902d7aec5b5fcf3d6c

https://blog.csdn.net/hon_3y/column/info/16477

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值