要通过注解统计接口调用耗时,可以按照以下步骤进行操作:
-
首先,在您的项目中引入一个AOP(面向切面编程)框架,比如Spring AOP或AspectJ。这些框架可以帮助您在方法执行前后插入额外的逻辑。
-
创建一个自定义的注解,用于标记需要被统计耗时的方法。例如,您可以创建一个名为@Timing的注解。
-
在AOP配置文件中,定义一个切面(Aspect),并使用切点表达式匹配包含@Timing注解的方法。切点表达式可以筛选出带有@Timing注解的方法,以便后续对其进行处理。
-
在切面中,使用@Around注解的方法中记录方法执行开始时间和结束时间,并计算耗时。
-
可以将耗时信息记录到日志中或者其他适当的位置,以供后续分析和监控。
- 创建一个Spring Boot项目,引入以下依赖(pom.xml):
<dependencies>
<!--其他依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--其他依赖-->
</dependencies>
- 创建一个自定义注解@Timing,用于标记需要统计耗时的方法。
package com.example.demo.aspect;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Timing {
}
- 创建一个切面类TimingAspect,用于处理被@Timing注解标记的方法。
package com.example.demo.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class TimingAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(TimingAspect.class);
@Around("@annotation(com.example.demo.aspect.Timing)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result = joinPoint.proceed();
long endTime = System.currentTimeMillis();
LOGGER.info("{} executed in {} ms", joinPoint.getSignature(), endTime - startTime);
return result;
}
}
- 创建一个Controller类,其中的方法使用@Timing注解标记。
package com.example.demo.controller;
import com.example.demo.aspect.Timing;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/hello")
@Timing
public String hello() {
// 模拟耗时操作
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello, World!";
}
}
- 在启动类上添加@EnableAspectJAutoProxy注解,开启AOP代理。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
当访问 http://localhost:8080/hello
时,TimingAspect中的logExecutionTime方法将会在接口执行前后打印日志,并记录接口调用耗时。