Arthas执行在线代码
文章目录
arthas 是阿里巴巴开源的一款监控诊断的神器,能实时监测应用内存、gc、线程的状态信息,并查看方法调用的出入参、异常,监测方法执行耗时等信息1。这篇文章中我们将借助 arthas 提供的 ognl 命令来执行在线代码。
安装
安装 arthas 很简单,只需要从官网下载并运行即可。
curl -O https://arthas.aliyun.com/arthas-boot.jar
java -jar arthas-boot.jar
选择所需要使用的程序,即会进入 arthas 的控制台。
如果碰到中文乱码,可以使用下面方式启动 arthas:
java -Dfile.encoding=UTF-8 -jar arthas-boot.jar
使用
ognl 命令能用于执行 ognl 表达式,但是需要获取类的 ClassLoader。所以关键在于获取类所在的 ClassLoader。为此准备了一个例子来讲解。
public class ArthasTest {
private static final ArthasTest instance = new ArthasTest();
private static List<Integer> staticList = Arrays.asList(1, 2);
private List<Integer> instanceList = Arrays.asList(3, 4);
public ArthasTest() {
}
public static ArthasTest getInstance() {
return instance;
}
public static String testStatic() {
return "执行方法testStatic()成功";
}
public String testInstance() {
return "执行方法testInstance()成功";
}
}
执行静态方法:
[arthas@14892]$ ognl -x 3 '@com.example.springstartertest.test.t2022.ArthasTest@testStatic()'
@String[执行方法testStatic()成功]
获取静态属性:
[arthas@14892]$ ognl -x 3 '@com.example.springstartertest.test.t2022.ArthasTest@staticList'
@ArrayList[
@Integer[1],
@Integer[2],
]
获取单例类。需要先获取实例对象,再执行实例方法:
[arthas@14892]$ ognl -x 3 '#ins=@com.example.springstartertest.test.t2022.ArthasTest@getInstance(),#ins.testInstance()'
@String[执行方法testInstance()成功]
获取单例类中的实例属性:
[arthas@14892]$ ognl -x 3 '#ins=@com.example.springstartertest.test.t2022.ArthasTest@getInstance(),#ins.instanceList'
@ArrayList[
@Integer[3],
@Integer[4],
]
对于 Spring 应用程序,则可以通过 Spring context 获取实例的 Bean2。 需要先增加一个类来获取 Spring context:
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext context;
public ApplicationContext getApplicationContext() {
return context;
}
@Override
public void setApplicationContext(ApplicationContext ctx) {
context = ctx;
}
}
测试类:
@Service("ArthasTest2")
public class ArthasTest2 {
public String run() {
return "执行方法run()成功";
}
}
调用 spring 管理的 bean 的方法:
[arthas@6648]$ ognl -x 3 '#springContext=@com.example.springstartertest.ApplicationContextProvider@context,#springContext.getBean("ArthasTest2").run()'
@String[执行方法run()成功]
对于 IDEA 用户来说,可以通过安装 “arthas idea” 插件,在指定方法或属性的位置右键直接获取 arthas 命令。
文章作者 梧桐碎梦
上次更新 2022-12-04 10:17:51