實現步驟只需要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方法上,添加對應的註解即可
效果:
很方便,不需要我們再去重複寫統計時間了。打開關閉也可以通過配置文件來控制