SpringBoot拦截器
最近项目中有一个需求,对来访的请求,进行计算,记录下业务处理时间。Spring Boot项目中使用拦截器,超级简单,再次说明一下用法。相信大家一看便懂。
1.继承 HandlerInterceptor 实现具体的处理逻辑
public interface HandlerInterceptor {
boolean preHandle(HttpServletRequest var1, HttpServletResponse var2, Object var3) throws Exception; //是否放行
void postHandle(HttpServletRequest var1, HttpServletResponse var2, Object var3, ModelAndView var4) throws Exception; //处理结束
void afterCompletion(HttpServletRequest var1, HttpServletResponse var2, Object var3, Exception var4) throws Exception; //在处理结束后执行,最后执行的方法
}
以下是我的处理逻辑
/**
* @Package: foxlife.base.interceptor
* @Description: 处理时间拦截器,记录下,接口处理时间
* @author: liuxin
* @date: 17/2/22 上午10:58
*/
@Component
public class ChanelInterceptor implements HandlerInterceptor {
private static Logger logger = LoggerFactory.getLogger(ChanelInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
logger.info("============================拦截器启动==============================");
request.setAttribute("starttime",System.currentTimeMillis());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
logger.info("===========================执行处理完毕=============================");
long starttime = (long) request.getAttribute("starttime");
request.removeAttribute("starttime");
long endtime = System.currentTimeMillis();
logger.info("============请求地址:"+request.getRequestURI()+":处理时间:{}",(endtime-starttime)+"ms");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
logger.info("============================拦截器关闭==============================");
}
}
2.配置拦截器到应用中
/**
* @Package: foxlife.base.config
* @Description: 配置拦截器
* @author: liuxin
* @date: 17/2/22 上午11:04
*/
@Configuration
public class MyInterceptorConfig extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ChanelInterceptor()).addPathPatterns("/**");
}
}
3.演示
2017-02-23 15:40:43.619 INFO 64568 --- [io-31024-exec-3] f.base.interceptor.ChanelInterceptor : ============================拦截器启动==============================
2017-02-23 15:40:43.621 INFO 64568 --- [io-31024-exec-3] f.base.interceptor.ChanelInterceptor : ===========================执行处理完毕=============================
2017-02-23 15:40:43.621 INFO 64568 --- [io-31024-exec-3] f.base.interceptor.ChanelInterceptor : ============请求地址:/error:处理时间:2ms
2017-02-23 15:40:43.621 INFO 64568 --- [io-31024-exec-3] f.base.interceptor.ChanelInterceptor : ============================拦截器关闭==============================