SpringAOP來監控service層中每個方法的執行時間
阿新 • • 發佈:2018-04-21
error try ref args 方法名 str ogg object PE
使用AOP來說,太方便了,並且特別適合這類場景。
代碼如下,這裏是將要統計的信息寫到log文件中,也可以設計成寫入表中。
package com.ecsoft.interceptor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class TimeInterceptor {
private static Logger log = LoggerFactory.getLogger(TimeInterceptor.class);
// service層的統計耗時切面,類型必須為final String類型的,註解裏要使用的變量只能是靜態常量類型的
public static final String POINT = "execution (* com.ecsoft.service..*Impl.*(..))" ;
/**
* 統計方法執行耗時Around環繞通知
* @param joinPoint
* @return
*/
@Around(POINT)
public Object timeAround(ProceedingJoinPoint joinPoint) {
// 定義返回對象、得到方法需要的參數
Object obj = null;
Object[] args = joinPoint.getArgs();
long startTime = System.currentTimeMillis ();
try {
obj = joinPoint.proceed(args);
} catch (Throwable e) {
log.error("統計某方法執行耗時環繞通知出錯", e);
}
// 獲取執行的方法名
long endTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
// 打印耗時的信息
this.printExecTime(methodName, startTime, endTime);
return obj;
}
/**
* 打印方法執行耗時的信息,如果超過了一定的時間,才打印
* @param methodName
* @param startTime
* @param endTime
*/
private void printExecTime(String methodName, long startTime, long endTime) {
long diffTime = endTime - startTime;
//超過1秒的記錄
if (diffTime > 1000) {
log.info(methodName + ":" + diffTime + " :ms");
}
}
}
SpringAOP來監控service層中每個方法的執行時間