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 {
        

    }

 

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