自定义MyThreadLocal和Spring Aop 切面编程在开发模式下打印出接口请求时间。
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
自定义MyThreadLocal
/**
*
* 自定义ThreadLocal.
*/
public class MyThreadLocal<T> extends ThreadLocal<T> {
@Override
public T get() {
remove();
return super.get();
}
public T get2() {
return super.get();
}
}
SpringAop 配置
/**
*
* 开发模式下打印出每个接口的请求时间(毫秒).
*/
@Aspect
@Component
@Slf4j
@Profile({"dev", "test"})// 设置 dev test 环境开启
public class ControllerAspect {
private static final MyThreadLocal<Long> time = new MyThreadLocal<Long>() {
@Override
protected Long initialValue() {
return System.nanoTime();
}
};
@Before("execution(* com.xxxxx.controller..*.*(..))")
public void beforeLog() {
time.get();
}
@After("execution(* com.xxxxx.controller..*.*(..))")
public void afterLog(JoinPoint joinPoint) {
log.error(joinPoint.toShortString() + " periods " + (int) ((System.nanoTime() - time.get2()) / 1000000) + "毫秒");
}
}
到此,就可以打印出每个controller层的接口的请求时间。
网友评论