溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring中StopWatch怎么用

發(fā)布時間:2021-09-27 15:04:44 來源:億速云 閱讀:115 作者:小新 欄目:編程語言

小編給大家分享一下Spring中StopWatch怎么用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

StopWatch簡單的秒表,允許多個任務(wù)的計(jì)時,暴露每個命名任務(wù)的總運(yùn)行時間和運(yùn)行時間。隱藏使用System.currentTimeMillis(),提高應(yīng)用程序代碼的可讀性并減少計(jì)算錯誤的可能性。

以下演示使用StopWatch記錄請求摘要日志信息:

@Slf4jpublic 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(), 總執(zhí)行時間    //sw.getTotalTimeMillis() - sw.getLastTaskTimeMillis(), 執(zhí)行方法體所需要的時間    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();  }}

以上是“Spring中StopWatch怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI