在SpringBoot rest API中记录执行所用时间

70gysomp  于 2023-02-28  发布在  Spring
关注(0)|答案(2)|浏览(137)

这可能是一个简单的解决方案,但我无法做到这一点。我需要记录我的请求在SpringBoot Rest API的整体执行时间。请求总是进入MainController总是可以退出两个地方-
1.主Restcontroller相同方法或

  1. ExceptionHandlerController处理程序方法
    我已经创建了一个自定义注解,并将其注入到ControllerExceptionController主方法中,并获取各个方法的运行时间。因此,问题就在这里。我需要将这些单独的时间相加来计算总时间,这是我不想要的。
    是否有其他方法可以轻松记录此信息。

特征类:

@Aspect
@Component
public class PointsAspect {

    private final static Logger logger = LoggerFactory.getLogger(PointsAspect.class);

    @Around("@annotation(annotation)")
    public Object logMethod(final ProceedingJoinPoint proceedingJoinPoint, final LogAround annotation)
            throws Throwable {
        final long start = System.currentTimeMillis();
        Object obj;
        try {
            logger.debug("Starting...! Method Name - " +proceedingJoinPoint.getSignature().getName());
            obj = proceedingJoinPoint.proceed();
        } finally {
            logger.debug("Exiting...! Method Name - " +proceedingJoinPoint.getSignature().getName() +"Execution Time in Milliseconds:> "+ String.valueOf(System.currentTimeMillis()-start));
        }
        return obj;
    }
}

标记接口:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAround {

}

我是这样注射的:

**ExceptionHandlerController.java**

@LogAround
@ExceptionHandler(HttpMessageNotReadableException.class)
public GenericFailureResponse missingRequestBodyException(HttpServletResponse response,
            HttpServletRequest request, Exception ex) throws IOException {
        GenericFailureResponse failureResponse =  new GenericFailureResponse();
        //TODO: exception logic
        return failureResponse;
}


**MainController.java**

@LogAround
 public String getTotalPoints(@RequestParam(required=true) long memberNo,
            HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        //TODO : some logic
        return "something";
 }
dluptydi

dluptydi1#

您可以使用简单的筛选器。

@Component
public class LogTimeFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long startTime = System.currentTimeMillis();
        chain.doFilter(request, response);
        long duration = System.currentTimeMillis() - startTime;
        System.out.println("Request take " + duration + " ms");
    }
}
rsl1atfo

rsl1atfo2#

我已经用注解和建议解决了这个问题。
首先需要添加这些依赖项
Boot
然后创建一个注解,如下所示

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Creator : Tanvir Chowdhury
 * Date    : 2023-02-23
 */
@Target(ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface TimeTraker {
}

然后在通知类中编写时间测量逻辑

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * Creator : Tanvir Chowdhury
 * Date    : 2023-02-23
 */

@Aspect
@Component
public class RequestResponseTimeTracker  {

    private static Logger logger = LoggerFactory.getLogger(RequestResponseTimeTracker.class);

    @Around("@annotation(com.reliantvalue.lake.security.TimeTraker)")
    public Object measureTime(ProceedingJoinPoint point) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Object object = point.proceed();
        stopWatch.stop();
        logger.debug("Execution Time taken by : " + point.getSignature().getName() + "() method is - "
                + stopWatch.getTotalTimeMillis() + " ms");
        return object;
    }
}

现在在rest控制器上使用注解TimeTracker,如下所示

@SneakyThrows
    @PostMapping
    @JsonView(View.Full.class)
    @TimeTraker
    public Loan createLoan(@CurrentUser User user,
                           @RequestParam(value = "type", required = false) String type,
                           @RequestParam(value = "wf", required = false) String wfId,
                           @RequestBody LoanCreateRequestDTO loanCreateRequest) {
}

输出将如下所示

2023-02-23 17:32:36,958 INFO  [http-nio-5000-exec-6] c.r.l.s.RequestResponseTimeTracker: Execution Time taken by : deleteLoan() method is - 3776 ms

相关问题