springboot中,如何利用AOP,实现函数执行时间打印并支持给annotation传递参数

需求:

利用AOP和annotation,实现当指定函数的执行时间超过阈值后,打印log

实现:

1,定一个带参数的annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogExecutionTime {
    public int threshold() default 2000;
}

2,定义一个类,实现@Aspect和@Around

@Aspect
@Component
@Slf4j
public class PerformanceAspect {

    @Around("@annotation(timeLogger)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint, LogExecutionTime timeLogger) throws Throwable {
        final long start = System.currentTimeMillis();
        final Object proceed = joinPoint.proceed();
        final long executionTime = System.currentTimeMillis() - start;
        if (timeLogger.threshold() <= executionTime) {
            log.warn("LogExecutionTime -- {} executed in {} ms", joinPoint.getSignature(), executionTime);
        } else {
            log.debug("LogExecutionTime -- {} executed in {} ms", joinPoint.getSignature(), executionTime);
        }
        return proceed;
    }

}

3,使用自定义的annotation

    @LogExecutionTime(threshold = 2000)
    @Transactional(rollbackFor = Exception.class)
    public void submitAnswers(String flowNumber, ArrayList<Answer> allAnswers) throws Exception {
        

    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章