简介:
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觉得可以很好的在短时间找到问题根源,进行方法级性能分析。
👍如果对你有帮助,给博主一个免费的点赞以示鼓励
欢迎各位🔎点赞👍评论收藏⭐️