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