javaAgent打包找不到premain类文件解决


agent 作用和开发

  • 可以用独立于应用程序之外的代理(agent)程序来监测和协助运行在JVM上的应用程序。这种监测和协助包括但不限于获取JVM运行时状态,替换和修改类定义等。

由此可知agent 功能不局限于监测jvm运行状态,我们还可以自定义他的功能,用处就自己想吧,比如 日志标签, 接口链路追踪, jvm信息, aop相关操作,服务器相关信息,接口访问前的监测,项目运行环境安装(配合脚本) 等一系列操作

agent 打包失败解决方案

作为新手 ,第一次实践一般都是根据网上的教程来的,于是我也是这样的,

  • 生成一个META-INF/MAINIFEST.MF文件
  • 重写一个premain方法
  • 在MAINIFEST.MF文件里面配置上必须的参数
       Manifest-Version: 1.0
       Premain-Class: UtilsAgent
       Created-By: 1.6.0_06
  • 打包 运行 测试 红一片,找不到的premain方法和类
    !!! 就很惨就很难受

于是研究一番,发现这些操作的最终目的就是吧上面配置文件里面的这个 Premain-Class 东西放进去,万变不离其踪
于是我用maven试类一下,果然可行,一下是正确的配置方式,用于记录踩坑经验

 <build>
    <finalName>utils-agent</finalName>
    <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.1.0</version>
        <configuration>
            <archive>
                <!--自动添加META-INF/MANIFEST.MF -->
                <manifest>
                    <addClasspath>true</addClasspath>
                </manifest>
                <manifestEntries>
                    <Premain-Class>vip.setsun.agent.UtilsAgent</Premain-Class>
                    <Agent-Class>vip.setsun.agent.UtilsAgent</Agent-Class>
                    <Can-Redefine-Classes>true</Can-Redefine-Classes>
                    <Can-Retransform-Classes>true</Can-Retransform-Classes>
                </manifestEntries>
            </archive>
        </configuration>
    </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>6</source>
                <target>6</target>
            </configuration>
        </plugin>
    </plugins>
    </build>

premain 方法

       public static void premain(String agentArgs, Instrumentation inst) {
        System.out.println("agentArgs : " + agentArgs);
        inst.addTransformer(new DefineTransformer());
    }

    static class DefineTransformer implements ClassFileTransformer {
        @Override
        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            System.out.println("premain load Class:" + className);
            System.out.println("premain loader:" + loader.toString());

            System.out.println("这里可以根据的自己的需求拿到想要的东西,比如 请求参数 相应参数 等。。。");


            return classfileBuffer;
        }
    }

demo案例

  • 将上面的两段代码打包就行了
  • 然后运行 idea 需要在vm options 配置 -javaagent:${your.path}/utils-agent.jar
  • 或者直接运行jar. java -javaagent:${your.path}/utils-agent.jar -jar test.jar
  • 访问main方法或者springboot接口即可看到相关日志


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM