RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
StopWatch怎么在Spring中使用

StopWatch怎么在Spring 中使用,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

铁山港网站制作公司哪家好,找创新互联!从网页设计、网站建设、微信开发、APP开发、自适应网站建设等网站项目制作,到程序开发,运营维护。创新互联自2013年起到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联

StopWatch简单的秒表,允许多个任务的计时,暴露每个命名任务的总运行时间和运行时间。隐藏使用System.currentTimeMillis(),提高应用程序代码的可读性并减少计算错误的可能性。

以下演示使用StopWatch记录请求摘要日志信息:

@Slf4j
public class PerformanceInteceptor implements HandlerInterceptor {
  private ThreadLocal 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(), 总执行时间
    //sw.getTotalTimeMillis() - sw.getLastTaskTimeMillis(), 执行方法体所需要的时间

    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();
  }
}

看完上述内容,你们掌握StopWatch怎么在Spring 中使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


网页标题:StopWatch怎么在Spring中使用
转载注明:http://sczitong.cn/article/jeogci.html