背景
每个接口SQL执行的耗时统计。
实现
定义注解
@Retention(RUNTIME)
@Target(METHOD)
public @interface CountTime {
}
定义实现
@Slf4j
@Aspect
@Component
public class TimeAspect {
/**
* 切点(表示只有加了@CountTime注解的方法,才会有统计接口耗时信息)
*/
@Pointcut("@annotation(com.xxx.config.aop.CountTime)")
public void couTime() {
}
/**
* 通知
*/
@Around("couTime()")
public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {//环绕通知
long start = System.currentTimeMillis();
Object res = proceedingJoinPoint.proceed();
long result = System.currentTimeMillis() - start;
log.info("耗时: {} 毫秒 by annotation, 方法 {} ", result, proceedingJoinPoint.getSignature());
return res;
}
// 生效目录
@Around("execution(* com.xxx.service.*.*(..))")
public Object timeAround(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = joinPoint.proceed();
long endTime = System.currentTimeMillis();
log.info("耗时: {} 毫秒 by expression, 方法 {} ", endTime - startTime, joinPoint.getSignature());
return result;
}
}
使用
- 扫描的目录生效
- 使用注解的生效