实现步骤只需要3步:
1.自定义注解
2.定义一个AOP切面
3.在需要统计时间的方法上,添加注解。
自定义一个注解。使用value来定义方法的名称,方便读日志。定义一个阈值,运行时间超过阈值,才会记录下来。
/**
* 统计方法运行的时间,单位毫秒
* @see CountTimeAop
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CountTime {
/**
* 在日志中打印的名称
* @return
*/
String value() default "";
/**
* 运行时间超过该值,才会打印
* @return 时间阈值
*/
long thresholdMS() default 0;
}
定义切面。可以通过配置项count.time.debug.switch=1/0来打开或关掉时间统计功能
@Aspect
@Component
@ConditionalOnProperty(value = "count.time.debug.switch", havingValue = "1")
public class CountTimeAop {
@Around("@annotation(countTime)")
public Object around(ProceedingJoinPoint joinPoint, CountTime countTime) throws Throwable{
long b = System.currentTimeMillis();
try{
return joinPoint.proceed();
}finally {
long e = System.currentTimeMillis();
long time = e-b;
if(time>countTime.thresholdMS())
System.out.println(countTime.value()+" 花费时长(ms):"+(e-b));
}
}
}
在需要的bean方法上,添加对应的注解即可
效果:
很方便,不需要我们再去重复写统计时间了。打开关闭也可以通过配置文件来控制