昨天,一位球友問我能不能給他解釋一下@SpringBootApplication 註解是什麼意思,還有Spring Boot 的運行原理,於是我就帶著他扒拉了一下這個註解的源碼,還有SpringApplication 類別的run() 方法的源碼,一下子他就明白了。
你別說,看原始碼的過程真的挺有趣,這不,我就發現了一個有趣的點。
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ...... stopWatch.stop(); }
Spring Boot 是用 StopWatch 來統計耗時的,而通常情況下,我們會用 System.currentTimeMillis() 來統計耗時,對吧?程式設計喵????開源專案裡就有這樣一段程式碼,在處理統一日誌處理切面的時候。
@Around("webLog()") public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis(); webLog.setSpendTime((int) (endTime - startTime)); }
對比之下,我們就能發現,JDK 提供的 System.currentTimeMillis() 沒有 Spring 提供的 StopWatch 簡潔、清晰。
尤其是在多任務的情況下,StopWatch 簡直好用到爆????!
// 创建一个 StopWatch 实例 StopWatch sw = new StopWatch("沉默王二是傻 X"); // 开始计时 sw.start("任务1"); Thread.sleep(1000); // 停止计时 sw.stop(); System.out.printf("任务1耗时:%d%s.\n", sw.getLastTaskTimeMillis(), "ms"); sw.start("任务2"); Thread.sleep(1100); sw.stop(); System.out.printf("任务2耗时:%d%s.\n", sw.getLastTaskTimeMillis(), "ms"); System.out.printf("任务数量:%s,总耗时:%ss.\n", sw.getTaskCount(), sw.getTotalTimeSeconds());
看到沒,是不是很簡單?
先new 一個StopWatch 物件
#再start 開始計時
任務1耗時:1002ms.#另外,StopWatch 還提供了一個sw.prettyPrint() 方法供打印出漂亮的格式化結果:任務2耗時:1105ms.
任務數:2,總耗時:2.107820109s.
StopWatch '沉默王二是傻X': running time = 2108529351 ns#有耗時,有佔用百分比,還有任務名,非常清楚。 除了 Spring,hutool 工具庫和 Apache common 工具包都提供了各自的 StopWatch。- ----------------------------------------------
ns % Task name
---------------------------------------------
1004338467 048% 任務1
1104190884 052% 任務2
public void stop() throws IllegalStateException { if (null == this.currentTaskName) { throw new IllegalStateException("Can't stop StopWatch: it's not running"); } final long lastTime = System.nanoTime() - this.startTimeNanos; this.totalTimeNanos += lastTime; this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime); if (null != this.taskList) { this.taskList.add(this.lastTaskInfo); } ++this.taskCount; this.currentTaskName = null; }
StopWatch sw = StopWatch.createStarted(); Thread.sleep(1000); System.out.printf("耗时:%dms.\n", sw.getTime());
// 暂停计时 sw.suspend(); System.out.printf("暂停耗时:%dms.\n", sw.getTime()); // 恢复计时 sw.resume(); System.out.printf("恢复耗时:%dms.\n", sw.getTime()); // 停止计时 sw.stop(); System.out.printf("总耗时:%dms.\n", sw.getTime()); // 重置计时 sw.reset(); // 开始计时 sw.start(); System.out.printf("重置耗时:%dms.\n", sw.getTime());
以上是Spring Boot原始碼如何實現StopWatch優雅統計量耗時的詳細內容。更多資訊請關注PHP中文網其他相關文章!