<bean id="timeAspect" class="com.demo.TimeCount"/>
<aop:config>
<aop:pointcut id="allPointcut" expression="execution (* com.demo..*(..))"/>
<aop:aspect order="99" ref="timeAspect">
<aop:around method="aroundMethod" pointcut-ref="allPointcut"/>
</aop:aspect>
</aop:config>
package com.demo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//@Aspect
//@Component
public class TimeCount {
private static Logger logger = LoggerFactory.getLogger(TimeCount.class);
private static long baseTime = System.currentTimeMillis();
public Object aroundAopMethod(ProceedingJoinPoint joinPoint) {
// 获取执行的方法名
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
// 定义返回对象、得到方法需要的参数
Object obj = null;
Object[] args = joinPoint.getArgs();
long startTime = System.currentTimeMillis() - baseTime;
System.out.println(methodName + " aop start at " + startTime);
try {
obj = joinPoint.proceed(args);
} catch (Throwable e) {
logger.error("统计某方法执行耗时环绕通知出错", e);
}
long endTime = System.currentTimeMillis() - baseTime;
long diffTime = endTime - startTime;
System.out.println(methodName + " aop finish at " + endTime + ", duration " + diffTime + "ms");
return obj;
}
/**
* 统计方法执行耗时Around环绕通知
*/
// @Around("execution (* com.demo..*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint) {
// 获取执行的方法名
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getDeclaringTypeName() + "." + signature.getName();
// 定义返回对象、得到方法需要的参数
Object obj = null;
Object[] args = joinPoint.getArgs();
long startTime = System.currentTimeMillis() - baseTime;
System.out.println(methodName + " start at " + startTime);
try {
obj = joinPoint.proceed(args);
} catch (Throwable e) {
logger.error("统计某方法执行耗时环绕通知出错", e);
}
long endTime = System.currentTimeMillis() - baseTime;
long diffTime = endTime - startTime;
System.out.println(methodName + " finish at " + endTime + ", duration " + diffTime + "ms");
return obj;
}
/**
* 打印方法执行耗时的信息,如果超过了一定的时间,才打印
*/
private void printExecTime(String methodName, long startTime, long endTime) {
}
}
使用Spring AOP来统计方法的执行时间
版权属于:wshon
本文链接:https://blog.wshon.com/2020/12/aop-time.html
转载时须注明出处及本声明
最新回复