Detailed explanation of spring stopwatch


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:

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

  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    StopWatch sw = new StopWatch();
    return true;

  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    StopWatch sw = stopWatchThreadLocal.get();
    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"{};{};{};{};{}ms;{}ms;{}ms", request.getRequestURI(), method,
        response.getStatus(), ex == null ? "-" : ex.getClass().getSimpleName(),
        sw.getTotalTimeMillis(), sw.getTotalTimeMillis() - sw.getLastTaskTimeMillis(),

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: 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 […]