说明:可自动打印方法运行时间。
使用:在方法上添加@RunningTime
注解。可以直接通过value
属性添加方法注解,或者添加Swagger 的ApiOperation注解,说明方法用途。都为空时,使用全限定方法名。
结果:
注解:@RunningTime
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 记录方法运行毫秒数
* @author chajiu
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RunningTime {
/**
* 方法注解,为空时搜索ApiOperation的注解,都为空时,使用全限定方法名
* @return
*/
String value() default "";
}
切面:
import co.yixiang.modules.system.aspect.aop.RunningTime;
import io.swagger.annotations.ApiOperation;
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;
import java.lang.reflect.Method;
@Component
@Aspect
@Slf4j
public class MethodRunningLogAspect {
ThreadLocal<Long> currentTime = new ThreadLocal<>();
@Pointcut("@annotation(co.yixiang.modules.system.aspect.aop.RunningTime)")
public void thisPointCut(){
}
@Around("thisPointCut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
currentTime.set(System.currentTimeMillis());
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
RunningTime runningTime = method.getAnnotation(RunningTime.class);
Object res = joinPoint.proceed();
String methodNote = "";
boolean flag=false;
if(!"".equals(runningTime.value())){
methodNote = runningTime.value();
flag = true;
}
if(!flag && apiOperation !=null){
methodNote = apiOperation.value();
}
if("".equals(methodNote)){
methodNote = joinPoint.getTarget().getClass().getName() + "."+method.getName();
}
log.info("耗时:"+methodNote +" {}毫秒",System.currentTimeMillis() - currentTime.get());
return res;
}
}