Java Instrument动态修改字节码入门-添加方法耗时监控

2024-04-25 03:58

本文主要是介绍Java Instrument动态修改字节码入门-添加方法耗时监控,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

平常在统计方法执行的耗时时长时,一般都是在方法的开头和结尾通过System.currentTimeMillis()拿到时间,然后做差值,计算耗时,这样不得不在每个方法中都重复这样的操作,现在使用Instrument,可以优雅的实现该功能。

一、编写Agent类

package com.jdktest.instrument;import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;public class AopAgentTest {static private Instrumentation _inst = null;  /** * The agent class must implement a public static premain method similar in principle to the main application entry point. * After the Java Virtual Machine (JVM) has initialized, * each premain method will be called in the order the agents were specified, * then the real application main method will be called.**/  public static void premain(String agentArgs, Instrumentation inst) {  System.out.println("AopAgentTest.premain() was called.");  /* Provides services that allow Java programming language agents to instrument programs running on the JVM.*/  _inst = inst; /* ClassFileTransformer : An agent provides an implementation of this interface in order to transform class files.*/  ClassFileTransformer trans = new AopAgentTransformer(); System.out.println("Adding a AopAgentTest instance to the JVM.");  /*Registers the supplied transformer.*/_inst.addTransformer(trans);  }  
}

代码功能详见注释。

二、编写ClassFileTransformer

ClassFileTransformer需要实现transform方法,根据自己的功能需要修改class字节码,在修改字节码过程中需要借助javassist进行字节码编辑。

javassist是一个开源的分析、编辑和创建java字节码的类库。通过使用javassist对字节码操作可以实现动态”AOP”框架。

关于java字节码的处理,目前有很多工具,如bcel,asm(cglib只是对asm又封装了一层)。不过这些都需要直接跟虚拟机指令打交道。javassist的主要的优点,在于简单,而且快速,直接使用java编码的形式,而不需要了解虚拟机指令,就能动态改变类的结构,或者动态生成类。

package com.jdktest.instrument;import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CodeConverter;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;public class AopAgentTransformer implements ClassFileTransformer{public byte[] transform(ClassLoader loader, String className,Class<?> classBeingRedefined, ProtectionDomain protectionDomain,byte[] classfileBuffer) throws IllegalClassFormatException {byte[] transformed = null;  System.out.println("Transforming " + className);  ClassPool pool = null;  CtClass cl = null;  try {  pool = ClassPool.getDefault();cl = pool.makeClass(new java.io.ByteArrayInputStream(  classfileBuffer));  //            CtMethod aop_method = pool.get("com.jdktest.instrument.AopMethods").
//                    getDeclaredMethod("aopMethod");
//            System.out.println(aop_method.getLongName());CodeConverter convert = new CodeConverter();if (cl.isInterface() == false) {  CtMethod[] methods = cl.getDeclaredMethods();  for (int i = 0; i < methods.length; i++) {  if (methods[i].isEmpty() == false) {  AOPInsertMethod(methods[i]);  }  }  transformed = cl.toBytecode();  }  } catch (Exception e) {  System.err.println("Could not instrument  " + className  + ",  exception : " + e.getMessage());  } finally {  if (cl != null) {  cl.detach();  }  }  return transformed;  }private void AOPInsertMethod(CtMethod method) throws NotFoundException,CannotCompileException {//situation 1:添加监控时间method.instrument(new ExprEditor() {  public void edit(MethodCall m) throws CannotCompileException {  m.replace("{ long stime = System.currentTimeMillis(); $_ = $proceed($$);System.out.println(\""+ m.getClassName() + "." + m.getMethodName()+ " cost:\" + (System.currentTimeMillis() - stime) + \" ms\");}");}}); //situation 2:在方法体前后语句
//      method.insertBefore("System.out.println(\"enter method\");");
//      method.insertAfter("System.out.println(\"leave method\");");}}

三、打包Agent jar包

因为agent依赖javassist,在build时需要加入<Boot-Class-Path>,pom文件如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.jdktest</groupId><artifactId>MyInstrument</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>instrument</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>javassist</groupId><artifactId>javassist</artifactId><version>3.8.0.GA</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency></dependencies><build>  <plugins>  <plugin>  <groupId>org.apache.maven.plugins</groupId>  <artifactId>maven-jar-plugin</artifactId>  <version>2.2</version>  <configuration>  <archive>  <manifestEntries>  <Premain-Class>com.jdktest.instrument.AopAgentTest</Premain-Class>  <Boot-Class-Path>E:/maven-lib/javassist/javassist/3.8.0.GA/javassist-3.8.0.GA.jar</Boot-Class-Path>  </manifestEntries>  </archive>  </configuration>  </plugin>  <plugin>  <artifactId>maven-compiler-plugin </artifactId >  <configuration>  <source> 1.6 </source >  <target> 1.6 </target>  </configuration>  </plugin>  </plugins>   </build> 
</project>

四、需要添加耗时监控的client

随意编写需要添加耗时监控的代码并打jar包。

package com.jdktest.SayHello;public class Target {public static void main(String[] args) {new Target().sayHello();}public void sayHello(){System.out.println("Hello, guys!");}
}

如果sayHello方法中又调用了同类中的方法或者别的类中的方法,这些被调用的方法的耗时仍可被监控到。

五、执行

在cmd下执行如下命令:

java -javaagent:E:/workspace/MyInstrument/target/MyInstrument-0.0.1-SNAPSHOT.jar -cp E:/workspace/SayHello/target/SayHello-0.0.1-SNAPSHOT.jar com.jdktest.SayHello.Target

六、执行结果

这里写图片描述

这篇关于Java Instrument动态修改字节码入门-添加方法耗时监控的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/933638

相关文章

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

MyBatis-Plus 中 nested() 与 and() 方法详解(最佳实践场景)

《MyBatis-Plus中nested()与and()方法详解(最佳实践场景)》在MyBatis-Plus的条件构造器中,nested()和and()都是用于构建复杂查询条件的关键方法,但... 目录MyBATis-Plus 中nested()与and()方法详解一、核心区别对比二、方法详解1.and()

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2