欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring StopWatch使用实例详解

程序员文章站 2023-01-25 18:15:40
这篇文章主要介绍了spring stopwatch使用实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 stopwatch简...

这篇文章主要介绍了spring stopwatch使用实例详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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

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

@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(), 总执行时间
    //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();
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。