Arthas常规用法实战指南:从基础操作到问题排查

作为Java开发者必备的诊断神器,Arthas的常规操作能力直接决定了线上问题排查效率。本文将系统讲解Arthas的核心操作模式,通过典型场景演示如何快速定位生产环境问题。

一、快速接入Arthas

1.1 启动方式对比

本地启动(开发环境推荐):

# 下载最新版本
wget https://arthas.aliyun.com/arthas-boot.jar

# 简单启动(自动列出Java进程)
java -jar arthas-boot.jar

生产环境附加(指定PID连接):

# 查找目标应用PID
ps -ef | grep java

# 精确附加到指定进程
./arthas-boot.jar <PID> --target-ip 0.0.0.0

隧道模式(安全环境使用):

# 启动隧道服务器
java -jar arthas-tunnel-server.jar

# 客户端连接配置
java -jar arthas-boot.jar --tunnel-server 'ws://127.0.0.1:7777/ws'
实践建议:生产环境建议通过--telnet-port 0 --http-port -1关闭非必要端口,仅使用隧道模式保证安全

二、高频诊断命令详解

2.1 方法级观测三剑客

耗时追踪(定位性能瓶颈):

# 监控com.example.UserService所有方法耗时>50ms的调用
trace com.example.UserService * '#cost>50' -n 3

# 追踪特定方法并打印参数
trace com.example.UserService getUserById params[0].length==10

实时观测(查看入参/返回值):

# 监控方法入参和返回值(-x表示展开层级)
watch com.example.UserService getUserById "{params,returnObj}" -x 2

# 按条件过滤观测(仅长度>10的入参)
watch com.example.UserService queryUser "params[0].length>10" -n 5

调用溯源(异常排查):

# 打印指定方法异常时的调用栈
stack com.example.UserService saveUser -e

# 显示调用路径耗时占比
stack com.example.UserService * '#cost>100'

2.2 线程/内存分析

线程快照分析

# 查看CPU占用TOP3线程
thread -n 3

# 分析指定线程状态(BLOCKED状态检测)
thread --state BLOCKED

# 查看线程调用栈(定位死锁)
thread -b

内存泄漏检测

# 生成堆转储文件(需配合MAT分析)
heapdump /tmp/dump.hprof

# 统计对象实例数
memory --classLoaderClass com.example.UserService

三、典型问题排查流程

3.1 CPU飙高问题(实战示例)

图1

具体操作

# 1. 定位CPU占用线程
$ thread -n 3
Thread 125: state=RUNNING cpuUsage=87% 
  at com.example.UserService.processData(UserService.java:42)

# 2. 查看线程栈
$ thread 125
Stack trace: 
UserService.processData() @45: 处理大数据量时未分页

# 3. 追踪方法耗时
$ trace com.example.UserService processData '#cost>100'

3.2 内存泄漏排查

# 1. 监控内存增长
dashboard -i 5000  # 5秒刷新观察内存曲线

# 2. 生成堆转储文件
heapdump --live /tmp/leak.hprof

# 3. 使用MAT分析支配树
# (定位到com.example.Cache持有大量User对象)

# 4. 验证缓存策略
watch com.example.Cache put "{params[0],params[1].size()}"

四、高效使用技巧

4.1 批处理操作

命令脚本化

# commands.txt内容:
watch com.example.Service doSomething params
trace com.example.Service * '#cost>200'

# 批量执行
batch -f commands.txt > audit.log

结果重定向

# 记录监控结果到文件
watch com.example.* * -x 2 > monitor.log &

# 后台持续监控(nohup方式)
nohup arthas-client -c "watch com.example.Service *" > output.log &

4.2 火焰图分析

# 启动性能采样(默认30秒)
profiler start --interval 5ms

# 生成SVG格式火焰图
profiler stop -f /tmp/flamegraph.svg

# 查看热点方法(结合trace验证)
profiler list
生产建议:采样间隔不宜过短(建议>1ms),避免影响应用性能

五、注意事项

  1. 性能影响

    • 避免同时开启多个watch/trace命令
    • 采样间隔设置合理值(如#cost>100而非#cost>10
  2. 安全规范

    # 安全启动示例
    java -jar arthas-boot.jar \
      --telnet-port 0 \          # 禁用telnet
      --http-port 8563 \         # 限制HTTP端口
      --tunnel-server 'wss://secure.com'  # 加密通道
  3. 资源清理

    # 退出前清理资源
    stop
    shutdown

通过以上实战方法,开发者可以快速掌握Arthas的核心诊断能力。建议在日常开发中建立标准化排查流程,将常用命令封装为脚本,提升线上问题响应效率。

评论已关闭