统计方法耗时

This commit is contained in:
Guoqs
2024-11-21 18:49:22 +08:00
parent 365466c82e
commit 1c42f253d0
8 changed files with 515 additions and 38 deletions

View File

@@ -1,41 +1,54 @@
package com.jsowell.framework.aspectj;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Aspect
@Order(1)
@Component// 使用spring容器进行管理
@Slf4j
public class CostTimeAspect {
private static final Logger logger = LoggerFactory.getLogger(CostTimeAspect.class);
/**
* 首先定义一个切点
*/
// @org.aspectj.lang.annotation.Pointcut("@annotation(com.counttime.annotation.entity.CostTime)")
@org.aspectj.lang.annotation.Pointcut("@annotation(com.jsowell.common.annotation.CostTime)")
public void countTime() {
// @org.aspectj.lang.annotation.Pointcut("@annotation(com.jsowell.common.annotation.CostTime)")
// public void countTime() {
//
// }
}
// @Around("countTime()")
// public Object doAround(ProceedingJoinPoint joinPoint) {
// Object obj = null;
// try {
// long beginTime = System.currentTimeMillis();
// obj = joinPoint.proceed();
// // 获取方法名称
// String methodName = joinPoint.getSignature().getName();
// // 获取类名称
// String className = joinPoint.getSignature().getDeclaringTypeName();
// log.info("统计方法耗时, 类:[{}], 方法:[{}], 耗时时间为:[{}ms]", className, methodName, (System.currentTimeMillis() - beginTime));
// } catch (Throwable throwable) {
// throwable.printStackTrace();
// }
// return obj;
// }
@Around("countTime()")
public Object doAround(ProceedingJoinPoint joinPoint) {
Object obj = null;
@Around("@annotation(com.jsowell.common.annotation.CostTime)")
public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
try {
long beginTime = System.currentTimeMillis();
obj = joinPoint.proceed();
// 获取方法名称
String methodName = joinPoint.getSignature().getName();
// 获取类名称
String className = joinPoint.getSignature().getDeclaringTypeName();
log.info("统计方法耗时, 类:[{}], 方法:[{}], 耗时时间为:[{}ms]", className, methodName, (System.currentTimeMillis() - beginTime));
} catch (Throwable throwable) {
throwable.printStackTrace();
return joinPoint.proceed();
} finally {
long endTime = System.currentTimeMillis();
long timeConsumed = endTime - startTime;
logger.info("方法 {} 耗时 {} 毫秒", joinPoint.getSignature().toShortString(), timeConsumed);
}
return obj;
}
}