「这是我参与2022首次更文挑战的第7天,活动详情查看:2022首次更文挑战」。
1.什么是arthas
arthas是阿里巴巴中间件团队开源出来的Java诊断工具。功能强大, 执行性能也是非常好.
2.Arthas 能为你做什么?
- 这个类从哪个 jar 包加载的?为什么会报各种类相关的 Exception?
- 我改的代码为什么没有执行到?难道是我没 commit?分支搞错了?
- 遇到问题无法在线上 debug,难道只能通过加日志再重新发布吗?
- 线上遇到某个用户的数据处理有问题,但线上同样无法 debug,线下无法重现!
- 是否有一个全局视角来查看系统的运行状况?
- 有什么办法可以监控到JVM的实时运行状态?
- 怎么快速定位应用的热点,生成火焰图?
3.入门
3.1 下载demo并运行
curl -O https://arthas.aliyun.com/arthas-demo.jar java -jar arthas-demo.jar
3.2 demo代码
是一个简单的程序,每隔一秒生成一个随机数,再执行质因数分解,并打印出分解结果。
package demo;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MathGame {
private static Random random = new Random();
public int illegalArgumentCount = 0;
public static void main(String[] args) throws InterruptedException {
MathGame game = new MathGame();
while (true) {
game.run();
TimeUnit.SECONDS.sleep(1);
}
}
public void run() throws InterruptedException {
try {
int number = random.nextInt()/10000;
List<Integer> primeFactors = primeFactors(number);
print(number, primeFactors);
} catch (Exception e) {
System.out.println(String.format("illegalArgumentCount:%3d, ", illegalArgumentCount) + e.getMessage());
}
}
public static void print(int number, List<Integer> primeFactors) {
StringBuffer sb = new StringBuffer(number + "=");
for (int factor : primeFactors) {
sb.append(factor).append('*');
}
if (sb.charAt(sb.length() - 1) == '*') {
sb.deleteCharAt(sb.length() - 1);
}
System.out.println(sb);
}
public List<Integer> primeFactors(int number) {
if (number < 2) {
illegalArgumentCount++;
throw new IllegalArgumentException("number is: " + number + ", need >= 2");
}
List<Integer> result = new ArrayList<Integer>();
int i = 2;
while (i <= number) {
if (number % i == 0) {
result.add(i);
number = number / i;
i = 2;
} else {
i++;
}
}
return result;
}
}
3.3 下载并启动arthas
curl -O https://arthas.aliyun.com/arthas-boot.jar java -jar arthas-boot.jar
3.4 相关命令
3.4.1.dashboard
dashboard 查看当前进程的信息
3.4.2.thread
thread 1 | grep 'main(' 打印线程ID 1的栈,通常是main函数的线程。
3.4.3. jad
jad demo.MathGame 通过jad来反编译Main Class
3.4.4.watch
watch demo.MathGame primeFactors returnObj 查看demo.MathGame#primeFactors函数的返回值
demo返回的日志
3.4.5.脚本
curl -sk https://arthas.aliyun.com/arthas-boot.jar -o ~/.arthas-boot.jar && echo "alias as.sh='java -jar ~/.arthas-boot.jar --repo-mirror aliyun --use-http 2>&1'" >> ~/.bashrc && source ~/.bashrc && echo "source ~/.bashrc" >> ~/.bash_profile && source ~/.bash_profile
#按照上列设置后,输入as.sh即可运行arthas