AOP
Spring是java面向对象编程的主流框架,其主要思想有两个:反转控制(IOC)和面向切面(AOP)。
日志中统计执行时间
直接通过毫秒差计算
- @Around环绕
// 我这里通过注解监听
@Pointcut("@annotation(***.***.ManagerLog)")
public void managerLogAop() {
}
@Around("managerLogAop()")
public Object timing(ProceedingJoinPoint joinPoint){
Object object;
long startTime = System.currentTimeMillis();
try{
object = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
return null;
}
long endTime = System.currentTimeMillis();
log.info("API 访问时长 " + (endTime - startTime) + " ms.");
return object;
}
- 结合@Before和@AfterReturning
private Long startTime;
// 我这里通过注解监听
@Pointcut("@annotation(***.***.ManagerLog)")
public void managerLogAop() {
}
@Before("managerLogAop()")
public void before() {
startTime = System.currentTimeMillis();
}
/**
* 正常返回通知
*/
@AfterReturning(value = "managerLogAop()", returning = "val")
public void afterReturning(JoinPoint joinPoint, Object val) {
// 拿到参数和返回结果等
log.info("API 访问时长 " + (System.currentTimeMillis() - startTime) + " ms.");
}
通过工具类
- @Around环绕
// 我这里通过注解监听
@Pointcut("@annotation(***.***.ManagerLog)")
public void managerLogAop() {
}
@Around("managerLogAop()")
public Object timing(ProceedingJoinPoint joinPoint){
Object object;
Stopwatch stopwatch1 = Stopwatch.createStarted();
try{
object = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
return null;
}
log.info("API 访问时长 " + stopwatch1.elapsed(TimeUnit.MILLISECONDS) + " ms.");
return object;
}
- 结合@Before和@AfterReturning
import com.google.common.base.Stopwatch;
private Stopwatch stopwatch;
// 我这里通过注解监听
@Pointcut("@annotation(***.***.ManagerLog)")
public void managerLogAop() {
}
@Before("managerLogAop()")
public void before() {
stopwatch = Stopwatch.createStarted();
}
/**
* 正常返回通知
*/
@AfterReturning(value = "managerLogAop()", returning = "val")
public void afterReturning(JoinPoint joinPoint, Object val) {
// 拿到参数和返回结果等
log.info("API 访问时长 " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms.");
}