Arthas实战指南:Java诊断与问题排查技巧之一
Arthas常规用法实战指南:从基础操作到问题排查
作为Java开发者必备的诊断神器,Arthas的常规操作能力直接决定了问题排查效率。本文将深入讲解Arthas最常用的功能场景,通过具体示例演示如何快速定位线上问题。
一、快速启动与连接
1. 基础启动方式
# 下载最新版本
wget https://arthas.aliyun.com/arthas-boot.jar
# 默认启动(自动列出Java进程)
java -jar arthas-boot.jar
# 指定PID连接(适用于多实例环境)
java -jar arthas-boot.jar <PID>
实践建议:生产环境推荐使用--target-ip
参数限制访问IP,避免安全风险:
java -jar arthas-boot.jar --target-ip 127.0.0.1
2. Web端连接方案
对于无法直接SSH的环境,可通过arthas-tunnel-server实现Web访问:
# 服务端启动
java -jar arthas-tunnel-server.jar
# 客户端连接
java -jar arthas-boot.jar --tunnel-server 'ws://127.0.0.1:7777/ws'
流程图解:
二、高频命令实战示例
1. 方法级性能分析
# 追踪方法内部调用路径(耗时>100ms的调用)
trace com.example.OrderService queryOrder "#cost>100" -n 3
# 监控方法入参和返回值(排除null值)
watch com.example.UserService getUserById "{params,returnObj}" "returnObj != null"
输出示例:
`---ts=2023-08-01 14:30:00;thread_name=main;id=1;is_daemon=false
`---[112ms] com.example.OrderService:queryOrder()
+---[90% 101ms] com.example.dao.OrderMapper:selectById()
`---[10% 11ms] com.example.util:formatResult()
实践建议:在高并发场景下,添加-n
参数限制输出次数避免刷屏:
trace com.example.Service * -n 5
2. 线程问题排查
# 查看CPU占用最高的3个线程
thread -n 3
# 分析指定线程的调用栈
thread <TID>
# 检测死锁情况
thread -b
典型输出:
Threads Total: 125, NEW: 0, RUNNABLE: 15, BLOCKED: 3
ID NAME STATE %CPU TIME
14 pool-1-thread-3 RUNNABLE 92% 3m42s
三、系统级问题排查流程
1. CPU飙高问题定位
# 1. 定位高CPU线程
thread -n 3
# 2. 查看线程堆栈
thread 14
# 3. 生成火焰图(需async-profiler)
profiler start
profiler stop --format html
火焰图解读技巧:
- 平顶表示性能瓶颈
- 宽度代表执行时间占比
- 从下往上追踪调用链
2. 内存泄漏排查
# 生成堆转储文件(默认输出到arthas-output目录)
heapdump --live /tmp/dump.hprof
# 配合MAT分析(需安装Eclipse Memory Analyzer)
jhat /tmp/dump.hprof
关键排查点:
- 重复创建的相同对象
- 非预期的对象引用链
- 集合类数据异常增长
四、高效运维技巧
1. 批量命令执行
# commands.txt内容示例:
watch com.example.Service * "{params,returnObj}"
trace com.example.Dao * "#cost>200"
# 批量执行
batch -f commands.txt > audit.log
2. 结果重定向与分析
# 将输出保存到文件(支持追加模式)
profiler start > /tmp/profiler.log 2>&1
# 结合grep过滤关键信息
thread | grep "BLOCKED"
五、生产环境最佳实践
性能采样控制:
- 避免同时开启多个采样命令
- 设置合理的采样频率(如
--sample 1000
)
安全防护措施:
# 禁用Telnet只保留HTTP java -jar arthas-boot.jar --telnet-port 0 --http-port 8563
资源清理方案:
# 退出时自动清理 shutdown --clean
通过以上常规用法的组合,可以解决80%以上的Java应用线上问题。建议将常用命令整理成cheatsheet,在应急响应时快速取用。
评论已关闭