当前位置: 移动技术网 > IT编程>开发语言>Java > Spring StopWatch使用实例详解

Spring StopWatch使用实例详解

2020年03月09日  | 移动技术网IT编程  | 我要评论

这篇文章主要介绍了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();
  }
}

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网