Spring StopWatch使用實(shí)例詳解
這篇文章主要介紹了Spring StopWatch使用實(shí)例詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
StopWatch簡(jiǎn)單的秒表,允許多個(gè)任務(wù)的計(jì)時(shí),暴露每個(gè)命名任務(wù)的總運(yùn)行時(shí)間和運(yùn)行時(shí)間。隱藏使用System.currentTimeMillis(),提高應(yīng)用程序代碼的可讀性并減少計(jì)算錯(cuò)誤的可能性。
以下演示使用StopWatch記錄請(qǐng)求摘要日志信息:
@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(), 總執(zhí)行時(shí)間
//sw.getTotalTimeMillis() - sw.getLastTaskTimeMillis(), 執(zhí)行方法體所需要的時(shí)間
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();
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot http請(qǐng)求注解@RestController原理解析
這篇文章主要介紹了SpringBoot http請(qǐng)求注解@RestController原理解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01
Spring攔截器之HandlerInterceptor使用方式
這篇文章主要介紹了Spring攔截器之HandlerInterceptor使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
SpringMVC后端返回?cái)?shù)據(jù)到前端代碼示例
這篇文章主要介紹了SpringMVC后端返回?cái)?shù)據(jù)到前端代碼示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
springboot @RequiredArgsConstructor的概念與使用方式
這篇文章主要介紹了springboot @RequiredArgsConstructor的概念與使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-09-09
Mybatis-plus中IService接口的基本使用步驟
Mybatis-plus是一個(gè)Mybatis的增強(qiáng)工具,它提供了很多便捷的方法來簡(jiǎn)化開發(fā),IService是Mybatis-plus提供的通用service接口,封裝了常用的數(shù)據(jù)庫(kù)操作方法,包括增刪改查等,下面這篇文章主要給大家介紹了關(guān)于Mybatis-plus中IService接口的基本使用步驟,需要的朋友可以參考下2023-06-06

