簡介:
????????Arthas是一款Java診斷工具,適用于多種場景,如接口響應變慢、CPU占用過高、熱更新需求等。其核心命令包括實時監控面板(dashboard)、線程狀態查看(thread)、方法調用鏈路追蹤(trace)、反編譯線上代碼(jad)、監控方法入參和返回值(watch)、熱更新代碼(redefine)、方法調用耗時統計(monitor)以及生成火焰圖(profiler)。
一、Arthas典型使用場景
-
日志沒報錯,但接口響應突然從?50ms?飆升到?5s
-
CPU 占用 100%,但無法快速定位是哪段代碼導致的
-
熱更新需求:修復 Bug 后不想重啟服務
二、核心命令
1. 實時監控面板:dashboard (查看實時線程、內存、GC狀態)
dashboard
2. 定位線程阻塞問題:thread
2.1 查看所有線程狀態
thread
?2.2?查看ID線程實際使用
thread ID
2.3 排查CPU占用最高的線程
thread -n 3
2.4 分析死鎖
thread -b
3. 追蹤方法調用鏈路:trace
追蹤指定方法的調用耗時
trace com.example.service.TestService getUserById
4. 反編譯線上代碼:jad
jad com.example.controller.TestController
5. 監控方法入參和返回值:watch
監控 getUserById 方法的入參和返回值
watch com.example.service.TestService getUserById "{params, returnObj}" -x 3
6. 熱更新代碼:redefine(不建議使用)
- 本地修改源碼后編譯為 .class 文件
- 上傳到服務器并熱加載
redefine /tmp/TestController.class
7. 方法調用耗時統計:monitor
每 60 秒統計一次 getUserById 的調用次數和平均耗時
monitor -c 60 com.example.service.TestService getUserById
8. 生成火焰圖(定位性能瓶頸)
:profiler(需要安裝C環境)
profiler startprofiler stop --format html
三、常見案例:
案例 1:CPU 突然飆升至 100%
1.查看 CPU 占用最高的線程
thread?-n?1
2.發現線程 ID 888 的堆棧
?
"http-nio-8080-exec-1"?Id=888?RUNNABLE? ? at com.example.TestService.calculate(...)
3.反編譯查看問題代碼
jad com.example.TestService calculate
案例 2:接口響應緩慢
1.追蹤方法調用鏈路
trace?com.example.controller.TestController getProfile
2.發現調用數據庫查詢耗時 2s
trace?com.example.TestService findById
3.檢查 SQL 是否命中索引
watch?com.example.TestService findById?"{params[0]}"?-x?1
案例 3:NoSuchMethodError
1.檢查類加載器是否加載了正確版本
sc -d com.example.TestService
2.重新加載修復后的類
redefine /tmp/TestService.class
四、注意事項
-
權限控制:生產環境限制 Arthas 使用權限,避免誤操作
-
性能影響:
watch/trace
?等命令會增加開銷,排查后及時關閉 -
安全風險:禁止將 Arthas 暴露在公網環境
五、總結
? ? ? ? 個人在使用Arthas覺得可以很好的在短時間找到問題根源,進行方法級性能分析。
???👍如果對你有幫助,給博主一個免費的點贊以示鼓勵
歡迎各位🔎點贊👍評論收藏??