← 返回首页

Arthas Java诊断工具

📂 java ⏱ 1 min 178 words

Arthas Java诊断工具

Arthas是阿里巴巴开源的Java在线诊断工具,无需修改代码即可实时诊断线上问题。

快速启动

# 下载并启动
curl -O https://arthas.aliyun.com/arthas-boot.jar
java -jar arthas-boot.jar

# 连接到目标Java进程
# 输入进程ID即可连接

核心命令

dashboard - 实时面板

# 查看实时信息
dashboard

# 输出示例:
# ID   NAME                          GROUP          PRIORITY  STATE
# 1    main                          main           5         WAITING
# 15   http-nio-8080-exec-1          main           5         TIMED_WAITING

thread - 线程分析

# 查看所有线程
thread

# 查看最忙的N个线程
thread -n 3

# 查看指定线程堆栈
thread <id>

# 查看死锁
thread -b

# 查看指定状态的线程
thread --state BLOCKED

trace - 方法调用追踪

# 追踪方法调用耗时
trace com.example.service.OrderService createOrder

# 过滤耗时超过100ms的调用
trace com.example.service.OrderService createOrder '#cost > 100'

# 追踪多个方法
trace com.example.service.OrderService createOrder,queryOrder

watch - 方法调用监控

# 观察方法返回值
watch com.example.service.OrderService createOrder returnObj

# 观察方法入参和返回值
watch com.example.service.OrderService createOrder '{params, returnObj}' -x 2

# 观察异常信息
watch com.example.service.OrderService createOrder throwExp

# 条件过滤
watch com.example.service.OrderService createOrder '{params[0].amount}' 'params[0].amount > 1000'

stack - 调用栈分析

# 查看方法调用栈
stack com.example.service.OrderService createOrder

# 带条件过滤
stack com.example.service.OrderService createOrder 'params[0].amount > 1000'

sc/sp - 类和Spring Bean

# 查看类加载信息
sc -d com.example.service.OrderService

# 查看Spring Bean
sc -d org.springframework.context.ApplicationContext
bean orderService

实战场景

排查慢SQL

# 追踪MyBatis执行
trace com.mysql.cj.jdbc.ClientPreparedStatement execute
watch com.mysql.cj.jdbc.ClientPreparedStatement execute '{params, throwExp}' -x 2

排查内存问题

# 查看堆内存使用
heapdump /tmp/heapdump.hprof

# 查看类加载情况
sc -d * | grep -i user

# 查看对象统计
vmtool --action getInstances --className com.example.entity.User --limit 10

热更新代码

# 反编译并修改
jad --source-only com.example.service.OrderService > /tmp/OrderService.java
# 编辑文件后
mc /tmp/OrderService.java -d /tmp
# 热更新
redefine /tmp/com/example/service/OrderService.class

小结

Arthas提供了丰富的在线诊断命令,无需重启即可排查线上Java应用的各种问题。