springboot 下注解+切面实现方法执行时间统计

首先定义一个注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CostTime {
    String value() default "";
}

然后定义一个切面处理类

@Aspect
@Component
public class CostTimeAOP {
    
    final static Logger log = LoggerFactory.getLogger(CostTimeAOP.class);

    @Pointcut("@annotation(cn.jesseyang.annotation.CostTime)")
    public void costTimePointCut(){}

    @Around("costTimePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        logCostTime(point, time);
        return result;
    }


    private void logCostTime(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("class:"+className+" method:"+methodName + " cost:"+time+"ms");
    }
}

你可能感兴趣的:(springboot 下注解+切面实现方法执行时间统计)