(一) Arthas 深度指南:Java 线上问题排查实战手册
Arthas 是阿里巴巴开源的 Java 诊断神器,能在不重启 JVM 的情况下进行实时问题诊断。以下是 Arthas 的核心功能与实战技巧:
一、Arthas 核心能力全景图
二、安装与启动
1. 快速安装
# 在线安装
curl -O https://arthas.aliyun.com/arthas-boot.jar
java -jar arthas-boot.jar
# 容器环境(K8s)
kubectl exec -it <pod-name> -- java -jar /tmp/arthas-boot.jar
2. 选择目标进程
[INFO] arthas-boot version: 3.7.1
[INFO] Found existing java process, please choose one and hit RETURN.
➜ 1: 25432 org.example.MainApp
➜ 2: 13456 com.alibaba.nacos.Nacos
三、线上问题排查实战场景
场景1:CPU 飙升定位
# 1. 查看实时线程状态
dashboard -i 1000 # 每秒刷新一次
# 2. 定位高CPU线程
thread -n 3 # 显示CPU占用Top3线程
# 3. 分析线程堆栈
thread 15 # 查看线程15的堆栈
# 4. 方法级CPU分析
profiler start # 启动采样
profiler stop # 生成火焰图
火焰图分析技巧:
- 平顶山:热点方法
- 宽度:方法执行时间占比
- 调用栈深度:方法调用链
场景2:内存泄漏排查
# 1. 堆内存分析
heapdump --live /tmp/heap.hprof # 导出堆快照
# 2. 对象统计
vmtool -x 3 --action getInstances \
--className java.lang.String \
--limit 10 # 查看String对象示例
# 3. 监控对象增长
monitor -c 5 'com.example.Service *' 'params.length > 0'
场景3:慢请求追踪
# 1. 方法耗时统计
trace com.example.Controller getData '#cost > 100' # 捕获>100ms的调用
# 2. 调用链分析
stack com.example.Service processRequest # 显示完整调用路径
# 3. 参数级监控
watch com.example.Dao queryDB \
'{params, returnObj, throwExp}' \
'#cost>50' -x 3 # 深度3层展开
输出示例:
method=com.example.Dao.queryDB location=AtExit
ts=2024-01-01 12:00:00; [cost=125.34ms] result=@ArrayList[
@Object[][
@String[user_123],
@Integer[10]
],
@User[User{name="John", age=30}],
null
]
四、Arthas 高级技巧
1. 热修复线上代码
# 1. 反编译方法
jad --source-only com.example.Service > /tmp/Service.java
# 2. 编辑修复代码
vim /tmp/Service.java
# 3. 热更新
redefine /tmp/Service.java
⚠️ 限制:不能修改方法签名/新增方法
2. 动态修改运行值
# 修改静态变量值
ognl '@com.example.Config@TIMEOUT=3000'
# 调用方法获取值
ognl '@com.example.Utils@getEnv()'
3. 类加载冲突诊断
# 查看类来源
sc -d com.example.SomeClass
# 类加载树分析
classloader -t
五、生产环境最佳实践
1. 安全防护措施
# 启动时绑定IP
java -jar arthas-boot.jar --telnet-ip 10.0.0.1
# 启用鉴权
java -jar arthas-boot.jar --username admin --password mypass
2. 自动化诊断脚本
# 批处理模式
echo "thread -n 3" | java -jar arthas-client.jar 127.0.0.1 3658
3. 容器化部署方案
# Dockerfile
FROM openjdk:11
RUN curl -o /opt/arthas.zip https://arthas.aliyun.com/download/latest_version?mirror=aliyun \
&& unzip /opt/arthas.zip -d /opt
ENTRYPOINT ["java", "-jar", "/opt/arthas-boot.jar"]
六、Arthas vs 传统工具对比
能力 | Arthas | Jstack/Jmap | VisualVM |
---|---|---|---|
无需重启 | ✅ | ❌ | ❌ |
动态追踪 | ✅ | ❌ | ⚠️ 有限 |
热修复 | ✅ | ❌ | ❌ |
容器支持 | ✅ 原生 | ⚠️ 需进入容器 | ❌ |
学习曲线 | 中等 | 简单 | 简单 |
生产安全 | ✅ 鉴权/IP绑定 | ❌ | ❌ |
七、实战案例库
案例1:Spring Bean 冲突
# 1. 查找重复Bean
ognl '#springContext=@com.example.App@getContext(),
#springContext.getBeanDefinitionNames()' \
| grep "userService"
# 2. 查看Bean来源
sc -d com.example.UserServiceImpl
案例2:MyBatis SQL 分析
# 监控SQL执行
watch org.apache.ibatis.executor.BaseExecutor query \
'{params[0], #cost}' -x 2
案例3:动态关闭日志
# 关闭DEBUG日志
logger --name ROOT --level INFO
八、性能优化技巧
# 限制输出量(防止OOM)
options batch-size 50 # 每次输出50条
# 异步执行命令
async-background trace com.example.Service *
# 结果缓存提升速度
options cache true
💡 黄金法则:生产环境操作遵循 LIFT 原则
- Log:记录所有操作
- Isolated:在隔离环境测试
- Fallback:准备回滚方案
- Throttle:限流操作影响
Arthas 通过 动态字节码增强技术(JavaAgent + ASM)实现无侵入诊断,已成为 Java 开发者线上排查的瑞士军刀。掌握其核心功能,能在分钟级定位生产环境疑难问题。
(二) Arthas 命令大全
Arthas 是 Java 线上诊断的神器,提供丰富的命令集用于实时问题排查。以下是全面的 Arthas 命令分类手册,包含使用示例和场景说明:
一、基础命令
命令 | 参数 | 说明 | 示例 |
---|---|---|---|
help | [command] | 查看命令帮助 | help thread |
version | - | 显示 Arthas 版本 | version |
quit | - | 退出当前会话 | quit |
stop | - | 关闭 Arthas 服务端 | stop |
keymap | - | 显示快捷键列表 | keymap |
history | - | 查看命令历史 | history |
session | - | 查看当前会话信息 | session |
reset | [class-pattern] | 重置增强类 | reset *Controller |
jobs | - | 管理后台任务 | jobs |
fg | %jobId | 恢复挂起的任务 | fg %1 |
bg | %jobId | 后台执行任务 | bg %2 |
二、JVM 监控命令
1. 仪表盘命令
dashboard [-i 刷新间隔ms] [-n 刷新次数]
示例:
dashboard -i 2000 # 每2秒刷新一次
dashboard -n 5 # 刷新5次后停止
2. 线程分析
命令 | 参数 | 说明 |
---|---|---|
thread | - | 显示所有线程 |
thread -n 3 | -n [top-n] | 显示最忙的前N个线程 |
thread -b | -b | 找出阻塞其他线程的线程 |
thread -i 1000 | -i [采样间隔] | 指定采样时间间隔 |
thread --state WAITING | –state [state] | 按状态过滤线程 |
3. 内存分析
# 堆内存直方图
memory
# 类实例统计
vmtool --action getInstances --className java.lang.String --limit 10
# 堆Dump
heapdump /tmp/dump.hprof
三、类与类加载器
1. 类信息查询
命令 | 参数 | 说明 |
---|---|---|
sc | -d [class-pattern] | 查看类信息 |
*sc -d Controller | -d | 显示详细信息 |
sc -f com.example.User | -f | 显示字段信息 |
*sc -E .Service | -E | 正则匹配类名 |
2. 方法信息
# 查看方法信息
sm java.lang.String toString
# 反编译类
jad com.example.UserService
# 输出到文件
jad --source-only com.example.UserService > UserService.java
3. 类加载器
# 类加载器树
classloader -t
# 查找资源
classloader -c 327a647b --resource logback.xml
# 加载的类
classloader -c 327a647b --load java.util.HashMap
四、方法诊断命令
1. 方法调用追踪
# 基本追踪
trace com.example.Service getData
# 过滤耗时
trace com.example.Service getData '#cost > 100'
# 限制层数
trace -E com.example.*|org.example.* getData -n 3
2. 方法执行监控
# 监控调用统计
monitor -c 5 com.example.Service getData
# 监控参数/返回值
watch com.example.Service getData '{params, returnObj}' -x 2
# 监控异常
watch com.example.Service getData '{throwExp}' -e
3. 调用路径分析
# 方法调用来源
stack com.example.Service processData
# 条件过滤
stack com.example.Service processData 'params[0].size() > 10'
五、高级诊断命令
1. 动态代码执行
# 执行OGNL表达式
ognl '@java.lang.System@getProperty("java.home")'
# 调用静态方法
ognl '@com.example.Utils@generateId()'
# 修改静态变量
ognl '@com.example.Config@TIMEOUT=3000'
2. 热修复代码
# 1. 反编译类
jad --source-only com.example.BugService > BugService.java
# 2. 编辑修复代码
vim BugService.java
# 3. 热更新
redefine BugService.java
3. 性能分析
# CPU火焰图
profiler start # 开始采样
profiler stop # 停止并输出
profiler list # 列出所有事件
profiler getSamples # 获取当前样本数
# 内存分配分析
profiler start --event alloc
六、系统与环境
1. 系统信息
# JVM信息
sysprop
sysenv
# 查看系统属性
sysprop java.version
sysprop user.country
# 修改系统属性
sysprop user.language zh
2. 日志控制
# 查看日志配置
logger
# 修改日志级别
logger --name ROOT --level ERROR
logger --class com.example --level DEBUG
3. 选项配置
# 查看所有选项
options
# 修改选项
options json-format true
options unsafe true
七、管道与批处理
1. 管道操作
# 组合命令
thread | grep 'main'
sysprop | grep java
watch *Service * '{params, returnObj}' | grep -E 'param1|return'
2. 批处理模式
# 执行脚本
java -jar arthas-client.jar 127.0.0.1 3658 -c "thread -n 3"
# 脚本文件
echo "thread -n 3" > commands.txt
java -jar arthas-client.jar 127.0.0.1 3658 -f commands.txt
八、高级场景命令
1. 反序列化诊断
# 监控反序列化
watch com.fasterxml.jackson.databind.ObjectMapper readValue '{params, returnObj}'
# 捕获异常
watch com.fasterxml.jackson.databind.ObjectMapper readValue '{throwExp}' -e
2. MyBatis SQL 分析
# 监控SQL执行
watch org.apache.ibatis.executor.BaseExecutor query '{params[0], #cost}'
# 查看SQL参数
watch org.apache.ibatis.executor.parameter.ParameterHandler setParameters params
3. Spring 上下文
# 获取Spring上下文
ognl '#springContext=@com.example.App@getContext(), #springContext'
# 查看Bean
ognl '#springContext.getBeanDefinitionNames()'
命令使用技巧
-
通配符使用
*
匹配任意包名/类名/方法名
..
匹配多层包名trace *..*Service get* # 追踪所有Service类的get开头方法
-
条件表达式
#cost
:方法执行耗时params
:方法参数数组returnObj
:返回值throwExp
:异常对象
watch *Service * 'params[0] != null && #cost > 50'
-
结果渲染控制
-x 2 # 展开层级深度 -n 3 # 执行次数限制 --exclude-class-pattern *Spring* # 排除类
安全提示:生产环境使用建议
- 启动时添加鉴权:
java -jar arthas-boot.jar --username admin --password mypass
- 绑定内网IP:
java -jar arthas-boot.jar --telnet-ip 10.0.0.1
- 操作前备份:
heapdump /backup/before.hprof
Arthas 通过 动态字节码增强技术 实现无侵入诊断,掌握这些命令能快速解决以下问题:
- CPU 飙升定位(
dashboard
→thread -n 3
) - 内存泄漏分析(
heapdump
→vmtool
) - 慢方法追踪(
trace #cost>100
) - 热修复代码(
jad
→redefine
) - 日志动态调整(
logger --level DEBUG
)
建议将本手册保存为参考速查表,遇到问题时快速定位合适命令!
tips >>
linux man 常用
command --help 常用