在我们的
web系统中,经常有统计API请求时间的需求。本文通过Spring AOP的方式来解决该问题,并给出具体代码实现。
原理讲解
使用AOP拦截所有Controller层的方法,定义一个环绕通知,在代理的方法(Controller里的方法)执行前后记录时间戳,并在执行后打印方法执行的时间。
代码实现
Application启动类上添加@EnableAspectJAutoProxy
package com.bimhome.asset.config;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* Created by hahazei on 2020/3/18.
*/
@Aspect
@Component
@Slf4j
public class PerformanceAspect {
//这里指定你需要拦截的地方,拦截controller上所有的方法
@Pointcut("execution(* com.xxx.xxx.controller..*(..))")
private void controllerOps() {
}
//这里定义一个环绕通知
@Around("controllerOps()")
public Object logPerformance(ProceedingJoinPoint pjp) throws Throwable {
long startTime = System.currentTimeMillis();
String name = "-";
String result = "Y";
try {
name = pjp.getSignature().toShortString();
return pjp.proceed();//这里执行被代理的方法
} catch (Throwable throwable) {
result = "N";
throw throwable;
} finally {
long endTime = System.currentTimeMillis();
//统计拦截方法执行的时长
log.info("{};{};{}ms", name, result, endTime - startTime);
}
}
}
执行结果
调用api请求,在终端可以看到对应日志。