实现方法:
1、硬解码(直接去编写代码部分)
2、注解+AOP
3、反射
4、运行时动态生产代码或修改代码(字节码改写(ASM、javassist))
这里以1和2来举例一下;
方法1--初级统计方法耗时
就是在请求方法中,调用前后调用System.currentTimeMillis()来统计时间
//记录该方法请求的开始时间
long startTime = System.currentTimeMillis();
。。。你写的方法的内容
//记录该方法的结束时间
long endTime = System.currentTimeMillis();
System.out.println("方法的总执行时间是:" + (endTime - startTime));
方法2--注解+AOP方式:
1、TimeConsume类
@Documented
@Retention(RetentionPolicy.RUNTIME)//运行时使用
@Target(ElementType.METHOD)//应用到方法级别
@Order(Ordered.HIGHEST_PRECEDENCE)//最高权限
public @interface TimeConsume {
//异常抛出时,是否统计,默认为false,不统计
boolean execeptionCheck() default false;
}
关于RetentionPolicy,可以点击进去查看所有的枚举
2、TimeConsumeContract类
@Aspect
@Component
public class TimeConsumeContract {
//只要是TimeConsume注解的所有类,所有方法,都进行执行
@Pointcut("execution(@io.renren.annotation.TimeConsume * *(..))")
public void methodPointCut() {
}
// 这里指的是围绕上面的methodPointCut方法去执行
/**
* @Param ProceedingJoinPoint 针对ProceedingJoinPoint 这个固定的切点
*/
@Around("methodPointCut()")
public Object joinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
//获取方法签名
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//获取方法名(不包含路径)
String name = methodSignature.getName();
//获取参数列表
Object[] args = joinPoint.getArgs();
//获取注解属性
boolean exceptionCheck = methodSignature.getMethod().getAnnotation(TimeConsume.class).execeptionCheck();
//获取方法对应的类的全限定名
String classPath = joinPoint.getTarget().getClass().getName();
long startTime = System.currentTimeMillis();
//获取继续执行被切方法
Object result = null;
if (exceptionCheck == true) {
try {
result = joinPoint.proceed(args);
long endTime = System.currentTimeMillis();
System.out.println("方法所在的地方" + classPath + "." + name);
System.out.println("方法耗时:" + (endTime - startTime) + "ms");
} catch (Exception e) {
e.printStackTrace();
}
} else {
result = joinPoint.proceed(args);
long endTime = System.currentTimeMillis();
System.out.println("方法所在的地方" + classPath + "." + name);
System.out.println("方法耗时:" + (endTime - startTime) + "ms");
}
return result;
}
}
3、在你需要使用的方法上使用该注解即可
例如:
@GetMapping(value = "/query")
@ApiOperation(value = "查询所有用例")
@TimeConsume
public Result queryAll() {
Result result = new Result();
List<TestCaseEntity> data = testCaseServiceImp.queryAll();
if (data != null && data.size() > 0) {
result.setData(data);
result.setCode(1);
result.setMsg("success");
} else {
result.setData(null);
result.setMsg("error");
result.setCode(0);
}
return result;
}