可以在Spring Boot中使用AOP(面向切面编程)和拦截器来获取完整的接口执行时长。以下是一些步骤:

  1. 创建一个切面类,并使用@Aspect注解进行标注。

  2. 在切面类中创建一个方法,并使用@Around注解进行标注。该方法将拦截所有被@RequestMapping注解的方法。

  3. 在方法中,使用System.currentTimeMillis()记录开始时间,并执行接口方法。

  4. 在接口方法执行后,再次使用System.currentTimeMillis()记录结束时间,并计算执行时长。

  5. 可以将执行时长记录到日志中,或者返回给前端。

以下是一个示例代码:

@Aspect
@Component
public class ExecutionTimeAspect {
 
    @Around("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
 
        Object proceed = joinPoint.proceed();
 
        long executionTime = System.currentTimeMillis() - start;
        System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
        return proceed;
    }
}

在上面的示例中,我们使用@Around注解来拦截所有被@RequestMapping注解的方法,并在方法执行前和执行后记录时间。最后,我们将执行时长记录到控制台中

springboot 如果获取完整的接口执行时长

原文地址: https://www.cveoy.top/t/topic/chYx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录