需求:
利用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 {
}