通过arthas vmtool 调用线上正在运行的service方法

场景

场景

具体描述

业务上有某个缓存需要删除,但是没有写删除 key 的远程接口

通过arthas执行 service 方法,删除缓存 key

1.前期准备

1.1下载arthas

官网地址

https://arthas.gitee.io/doc/quick-start.html

下载运行

curl -O https://arthas.aliyun.com/arthas-boot.jar java -jar arthas-boot.jar

通过arthas vmtool 调用线上正在运行的service方法_缓存

1.2 idea安装arthas插件

通过arthas vmtool 调用线上正在运行的service方法_远程调用_02

1.3 写一个普通sum方法

通过arthas vmtool 调用线上正在运行的service方法_远程调用_03

启动这个应用

通过arthas vmtool 调用线上正在运行的service方法_jar_04

1.4 启动arthas并attach上helloworld进程

通过arthas vmtool 调用线上正在运行的service方法_jar_05

选择1

通过arthas vmtool 调用线上正在运行的service方法_jar_06

2. 实际操作

例如我们需要远程调用下这个sum方法,但是controller没用写调用sum方法接口,重新发版有风险且太慢了,于是可以利用arthas直接远程调用sum

通过arthas vmtool 调用线上正在运行的service方法_远程调用_07

上面我们已经启动了arthas且attach上了helloworld进程

2.1 获取UserService的classLoaderHash

此时需要先获取UserService的classLoaderHash 用于后续我们指定访问这个方法

sc -d com.example.helloworld.service.UserService

通过arthas vmtool 调用线上正在运行的service方法_缓存_08

classLoaderHash 18b4aac2

2.2 通过idea arthas插件获取执行方法的命令

通过arthas vmtool 调用线上正在运行的service方法_缓存_09

通过arthas vmtool 调用线上正在运行的service方法_远程调用_10

复制出来是这个样子

vmtool -x 3 --action getInstances --className com.example.helloworld.service.UserService --express 'instances[0].sum(new com.example.helloworld.controller.User())' -c 18b4aac2

参数解释

-x 3返回参数展开形式的,默认1,设置3,方便观察返回结果

-c xxx指定classLoaderHash

2.3 完善下,加上传递参数,例如传递年龄为3

vmtool -x 3 --action getInstances --className com.example.helloworld.service.UserService --express 'instances[0].sum(new com.example.helloworld.controller.User("zhangsan",3))' -c 18b4aac2

通过arthas vmtool 调用线上正在运行的service方法_缓存_11

通过arthas vmtool 调用线上正在运行的service方法_jar_12