Java Agent调试

最近在学习Java Agent,记录一下如何调试。

一、写一个Agent

1、编写一个Java类,并包含如下两个方法中的任一个:

public static void premain(String agentArgs, Instrumentation inst); //【1】
public static void premain(String agentArgs); //【2】
其中,【1】和【2】同时存在时,【1】会优先被执行,而【2】则会被忽略。

具体使用如下代码:

import java.lang.instrument.Instrumentation;
public class MyAgent {
    public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println("this is an agent.");
        System.out.println("args:" + agentArgs + "\n");
    }
}

2、jar打包
在代码的resources目录下添加META-INF/MANIFEST.MF文件。其目的是指定Premain-Class的类。

Manifest-Version: 1.0
Premain-Class: com.zl.unit1.MyAgent
Can-Redefine-Classes: true

3、在pom.xml中配置打包的相关配置。

    <packaging>jar</packaging>
    <build>
        <finalName>my-agent</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <archive>
                        <index>true</index>
                        <manifestFile>
                            src/main/resources/META-INF/MANIFEST.MF
                        </manifestFile>
                        <manifest>
                            <addDefaultImplementationEntries/>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
    </plugins>
    </build>

最后,执行mvn clean package,就能生成一个my-agent.jar。
这里写图片描述

二、运行Agent

新建一个测试类。如下:

public class AgentTest {
    public static void main(String[] args) {
        System.out.println("this is main");
    }
}

命令行运行:java -javaagent: 文件位置 [=参数]
idea运行:如果是Idea中,按如下配置。
这里写图片描述

运行结果如下:我这里重复加载了两次Agent,但是传入的参数不同。

this is an agent.
args:first

this is an agent.
args:second

this is main

三、调试Agent

1、使用 Spring Boot 创建一个简单的 Web 项目。AgentDemo用户创建Agent类,agent-test用于外部启动执行Agent类,如下图 :
这里写图片描述
友情提示 :这里一定要注意下。创建的 Web 项目,使用 IntelliJ IDEA 的菜单 File / New / Module 或 File / New / Module from Existing Sources ,保证 Web 项目和 Agent 项目平级。这样,才可以使用 IntelliJ IDEA 调试 Agent 。

扫描二维码关注公众号,回复: 10814042 查看本文章

2、设置线程模式下的断点
这里写图片描述

3、执行
运行 Web 项目的 Application 的 #main(args) 方法,并增加 JVM 启动参数,-javaagent:F:\IdeaWorkSpace\AgentDemo\target\my-agent.jar。如下图 :
这里写图片描述

debug模式运行就可以顺利调试agent代码了。

发布了45 篇原创文章 · 获赞 18 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_26761587/article/details/78817745