如何手寫一個攔截器呢。假設我如今須要一個計時攔截器,我想把每一次調用服務鎖花費的時間打印到控制檯,我該怎麼作呢?nginx
他們三個各有優缺點,須要根據本身的業務需求來選擇最適合的攔截機制。 redis
好了下面開始正文。spring
/**
* Time 時間攔截器(比時間過濾器準))
* Created by Fant.J.
*/
@Component
public class TimeInterceptor implements HandlerInterceptor {
//controller 調用以前被調用
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
System.out.println("preHandle");
System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
System.out.println(((HandlerMethod)handler).getMethod().getName());
httpServletRequest.setAttribute("startTime",System.currentTimeMillis());
return true;
}
//controller 調用以後被調用,若是有異常則不調用
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
long startTime = (long) httpServletRequest.getAttribute("startTime");
System.out.println("時間攔截器耗時:"+(System.currentTimeMillis() -startTime));
}
//controller 調用以後被調用,有沒有異常都會被調用,Exception 參數裏放着異常信息
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("afterCompletion");
long startTime = (long) httpServletRequest.getAttribute("startTime");
System.out.println("時間攔截器耗時:"+(System.currentTimeMillis() -startTime));
}
}
複製代碼
代碼解釋:springboot
可是值寫這個處理攔截器還不行,還須要進一步的配置,請看下面一段代碼:bash
/**
* 引入第三方過濾器 將其放入spring容器
* Created by Fant.J.
*/
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
// 注入Time 攔截器
@Autowired
private TimeInterceptor timeInterceptor;
//添加攔截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//往攔截器註冊器裏添加攔截器
registry.addInterceptor(timeInterceptor);
}
複製代碼
首先咱們繼承WebMvcConfigurerAdapter類,重寫它的addInterceptors()方法,該方法是添加攔截器至Spring容器中。 而後調用攔截器註冊器InterceptorRegistry 進行註冊。併發
SpringCloud springboot nginx redis框架
Java NIO教程 Java reflection 反射詳解 Java併發學習筆錄 Java Servlet教程 jdbc組件詳解 Java NIO教程 Java語言/版本 研究ide