一个简单的性能拦截器

一个简单的性能拦截器

Interceptor拦截器方式(也可以通过web拦截器)

@Slf4j
public class PerformanceInteceptor implements HandlerInterceptor {
    private ThreadLocal<StopWatch> stopWatch = new ThreadLocal<>();

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

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        stopWatch.get().stop();
        stopWatch.get().start();
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        StopWatch sw = stopWatch.get();
        sw.stop();
        String method = handler.getClass().getSimpleName();
        if (handler instanceof HandlerMethod) {
            String beanType = ((HandlerMethod) handler).getBeanType().getName();
            String methodName = ((HandlerMethod) handler).getMethod().getName();
            method = beanType + "." + methodName;
        }
        log.info("{};{};{};{};{}ms;{}ms;{}ms", request.getRequestURI(), method,
                response.getStatus(), ex == null ? "-" : ex.getClass().getSimpleName(),
                sw.getTotalTimeMillis(), sw.getTotalTimeMillis() - sw.getLastTaskTimeMillis(),
                sw.getLastTaskTimeMillis());
        stopWatch.remove();
    }
}

启动类

public class WaiterServiceApplication implements WebMvcConfigurer {
	public static void main(String[] args) {
		SpringApplication.run(WaiterServiceApplication.class, args);
	}
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new PerformanceInteceptor())
				.addPathPatterns("/coffee/**").addPathPatterns("/order/**");
	}
}

AOP(较为繁琐,不推荐)

@Aspect
@Slf4j
@Component
public class ControllerMonitor {

    @Autowired
    ControllerMonitorService monitorService;

    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void monitorGet(){}

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void monitorPost(){}

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PutMapping)")
    public void monitorPut(){}

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void monitorRequest(){}

    public Object controllerMonitor(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("开始时间:"+ DateUtils.getDateStr(new Date()));
        String className=joinPoint.getSignature().getDeclaringTypeName();
        log.info("调用类:"+className);
        String methodName = ((MethodSignature) joinPoint.getSignature()).getMethod().getName();
        log.info("调用方法:"+methodName);
        String args= Arrays.toString(joinPoint.getArgs());
        log.info("调用参数:"+args);
        LocalDateTime startTime= LocalDateTime.now();
        Object object=joinPoint.proceed();
        LocalDateTime endTime= LocalDateTime.now();
        Long cost= Duration.between(startTime,endTime).toMillis();
        ControllerMonitorVO controllerMonitorVO=new ControllerMonitorVO();
        controllerMonitorVO.setCreateTime(LocalDateTime.now());
        controllerMonitorVO.setControllerName(className);
        controllerMonitorVO.setMethodName(methodName);
        controllerMonitorVO.setMethodArgs(args);
        controllerMonitorVO.setStartTime(startTime);
        controllerMonitorVO.setEndTime(endTime);
        controllerMonitorVO.setCost(cost);
        monitorService.save(controllerMonitorVO);
        log.info("结束时间:"+ DateUtils.getDateStr(new Date()));
        return object;
    }

    @Around(value="monitorGet()")
    public Object aroundGet(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("---进入get请求");
        Object object=controllerMonitor(joinPoint);
        log.info("---离开get请求");
        return object;
    }
    @Around(value="monitorPost()")
    public Object aroundPost(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("---进入post请求");
        Object object=controllerMonitor(joinPoint);
        log.info("---离开post请求");
        return object;
    }
    @Around(value="monitorPut()")
    public Object aroundPut(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("---进入put请求");
        Object object=controllerMonitor(joinPoint);
        log.info("---离开put请求");
        return object;
    }
    @Around(value="monitorRequest()")
    public Object aroundRequest(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("---进入request请求");
        Object object=controllerMonitor(joinPoint);
        log.info("---离开request请求");
        return object;
    }
}

vo

public class ControllerMonitorVO extends IdVO {
    /**
     * controller类名
     */
    private String controllerName;

    /**
     * 方法名
     */
    private String methodName;

    /**
     * 参数
     */
    private String methodArgs;

    /**
     * 开始时间
     */
    private LocalDateTime startTime;

    /**
     * 结束时间
     */
    private LocalDateTime endTime;

    /**
     * 耗时
     */
    private Long cost;
}
上一篇:【项目笔记】AOP在项目中打日志的应用


下一篇:spring aop事件两种实现方式,带注解和不带注解