方法耗时是接口优化比较重要的一个点了。
一般的方法耗时处理会直接在方法调用前后进行记然后进行计算,然后通过计算求出最后方法的执行时间,这是最简单最直接的解决方式了。如下是比较传统的处理方式:
long startTime = System.currentTimeMillis();
/** 调用处理方法*/
this.testMet(Object object);
long endTime = System.currentTimeMillis();
log.info("操作执完毕,耗时:" + (startTime- endTime ) + "毫秒 !");
但是这种方式会写重复的很多代码!造成代码冗余,发布线上前进行删除也比较麻烦!
相同是处理操作可以用切面的形式进行处理,分为3部分:
1、创建切面自定义 方法耗时的注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @description: 方法耗时
* @author HuaShangJin
* @date 2022/7/20 15:17
* @version 1.0
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TimeConsuming {
}
2、创建对应的aop切面处理类,切面的切入方式选择环绕增强。
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
/**
* @description: 方法耗时 切面处理类
* @author HuaShangJin
* @date 2022/7/20 15:50
* @version 1.0
*/
@Aspect
@Component
@Slf4j
public class TimeConsumingAspect {
// 定义切点
@Pointcut("@annotation(com.nos.imt.aspect.timeConsuming.TimeConsuming)")
public void doAspect() {
}
/**
* @description: 定义环绕增强
* @param: joinPoint
* @return: java.lang.Object
* @author HuaShangJin
* @date: 2022/7/20 15:19
*/
@Around("doAspect()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
// 开始时间
long startTime = System.currentTimeMillis();
// 值是被拦截方法的返回值
Object proceed = joinPoint.proceed();
// 计算执行时间
long endTime = System.currentTimeMillis();
//获取类的字节码对象,通过字节码对象获取方法信息
Class<?> targetCls = joinPoint.getTarget().getClass();
//获取方法签名(通过此签名获取目标方法信息)
MethodSignature ms = (MethodSignature) joinPoint.getSignature();
String method = targetCls.getName() + "." + ms.getName() + "()";
log.info("*******@TimeConsuming注解切入:" + method + "方法耗时:" + (endTime - startTime) + "毫秒 !*******");
return proceed;
}
}
3、在方法上使用该注解即可。
@TimeConsuming
public List<TeamUserVo> testMethod(Long id) {
System.out.println("我是测试方法!");
}
完毕~