最近开发要求接口响应时间不能超过1s,在此写了一个耗时注解,直接注解到接口方法上
添加一个annotation
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CostTime {
}
添加aspect
最开始此处添加了异常捕获造成接口获取不到异常消息或者获取不到自定义消息
@Aspect
@Component
@Slf4j
public class CostTimeAspect {
//此处修改为完整包路径
@Pointcut("@annotation(cn.*.annotation.CostTime)")
public void costTime(){}
@Around("costTime()")
public Object costTimeAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object obj = null ;
Long beginTime = System.currentTimeMillis() ;
obj = joinPoint.proceed() ;
//获取识别信息
String className = joinPoint.getSignature().getDeclaringTypeName() ;
String methodName = joinPoint.getSignature().getName();
//耗时
Long useTime = System.currentTimeMillis()-beginTime ;
log.info("类:[{}],方法:[{}] ,接口耗时:[{}ms]",className,methodName,useTime);
return obj ;
}
}
调用
@ApiOperation("详情")
@GetMapping("/info/{serial}")
@ApiResponses({
@ApiResponse(code = 200,message = "ok",response = MaterialInfoRes.class)
})
@CostTime
public Result info(@PathVariable("serial")String serial){
MaterialInfoRes res = materialService.info(serial) ;
return Result.ok().put("data",res) ;
}
调用结果
针对耗时多的接口再细分析处理