记录请求时间
统计记录接口的请求时间:
package com.onloon.data.centralization.web.interceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.onloon.summer.common.utils.JsonUtil; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 请求拦截器 * * @author <a href="mailto:taojiagui@loonxi.com">云启</a> * @version 1.0 2017年5月12日 * @since 1.0 */ public class RequestInterceptor implements HandlerInterceptor { private Logger logger = LoggerFactory.getLogger(RequestInterceptor.class); // 存储请求额外信息 private final ThreadLocal<RequestHolder> requestThread = new ThreadLocal<RequestHolder>(); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String uri = request.getRequestURI(); if (logger.isInfoEnabled()) { logger.info("RequestInterceptor.preHandle execute uri={}", uri); } RequestHolder holder = new RequestHolder(); holder.setStartTime(System.currentTimeMillis()); holder.setUri(uri); requestThread.set(holder); logger.info("preHandle 当前线程:{},holder信息={}", Thread.currentThread().getName(), JsonUtil.toJsonString(holder)); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { RequestHolder holder = getRequestHolder(); logger.info("afterCompletion 当前线程:{},holder信息={},当前时间={},请求消耗时间={} ms", Thread.currentThread().getName(), JsonUtil.toJsonString(holder), System.currentTimeMillis(), (System.currentTimeMillis() - holder.getStartTime())); } private RequestHolder getRequestHolder() { RequestHolder holder = requestThread.get(); if (holder == null) { holder = new RequestHolder(); requestThread.set(holder); } return holder; } }