Detailed explanation of spring stopwatch

Time:2020-7-2

This article mainly introduces how to use spring stopwatch in detail. The example code is introduced in detail, which has certain reference value for everyone’s study or work. Friends in need can refer to it

Stopwatch is a simple stopwatch that allows multiple tasks to be timed, exposing the total run time and run time of each named task. Hidden use System.currentTimeMillis (), improve the readability of application code and reduce the possibility of computational errors.

The following demonstration uses stopwatch to record request summary log information:

@Slf4j
public class PerformanceInteceptor implements HandlerInterceptor {
  private ThreadLocal<StopWatch> stopWatchThreadLocal = new ThreadLocal<>();

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    StopWatch sw = new StopWatch();
    stopWatchThreadLocal.set(sw);
    sw.start();
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    stopWatchThreadLocal.get().stop();
    stopWatchThreadLocal.get().start();
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    StopWatch sw = stopWatchThreadLocal.get();
    sw.stop();
    String method = handler.getClass().getSimpleName();
    if (handler instanceof HandlerMethod) {
      String beanType = ((HandlerMethod) handler).getBeanType().getName();
      String methodName = ((HandlerMethod) handler).getMethod().getName();
      method = beanType + "." + methodName;
    }
    // sw.getTotalTimeMillis (), total execution time
    // sw.getTotalTimeMillis () -  sw.getLastTaskTimeMillis (), the time required to execute the method body

    log.info("{};{};{};{};{}ms;{}ms;{}ms", request.getRequestURI(), method,
        response.getStatus(), ex == null ? "-" : ex.getClass().getSimpleName(),
        sw.getTotalTimeMillis(), sw.getTotalTimeMillis() - sw.getLastTaskTimeMillis(),
        sw.getLastTaskTimeMillis());
    stopWatchThreadLocal.remove();
  }
}

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.

Recommended Today

Think about open source project promoting rust search extension: quickly search rust documents in the browser address bar

Open source project name:Rust Search Extension Introduction to open source projects:Quick search for rust documents in the browser address barOpen source project type:teamProject creation time:2020 GitHub data:375 Star,18 ForkGitHub address:https://github.com/huhu/rust-search-extension Rust search extension is a plug-in that can quickly search rust documents, Crites, built-in properties and error codes in the browser address bar. It supports […]