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

相关文章

Spring Boot整合Redis注解实现增删改查功能(Redis注解使用)

《SpringBoot整合Redis注解实现增删改查功能(Redis注解使用)》文章介绍了如何使用SpringBoot整合Redis注解实现增删改查功能,包括配置、实体类、Repository、Se... 目录配置Redis连接定义实体类创建Repository接口增删改查操作示例插入数据查询数据删除数据更

Java Lettuce 客户端入门到生产的实现步骤

《JavaLettuce客户端入门到生产的实现步骤》本文主要介绍了JavaLettuce客户端入门到生产的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 目录1 安装依赖MavenGradle2 最小化连接示例3 核心特性速览4 生产环境配置建议5 常见问题

使用python生成固定格式序号的方法详解

《使用python生成固定格式序号的方法详解》这篇文章主要为大家详细介绍了如何使用python生成固定格式序号,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以参考一下... 目录生成结果验证完整生成代码扩展说明1. 保存到文本文件2. 转换为jsON格式3. 处理特殊序号格式(如带圈数字)4

Java使用Swing生成一个最大公约数计算器

《Java使用Swing生成一个最大公约数计算器》这篇文章主要为大家详细介绍了Java使用Swing生成一个最大公约数计算器的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下... 目录第一步:利用欧几里得算法计算最大公约数欧几里得算法的证明情形 1:b=0情形 2:b>0完成相关代码第二步:加

Java 的ArrayList集合底层实现与最佳实践

《Java的ArrayList集合底层实现与最佳实践》本文主要介绍了Java的ArrayList集合类的核心概念、底层实现、关键成员变量、初始化机制、容量演变、扩容机制、性能分析、核心方法源码解析、... 目录1. 核心概念与底层实现1.1 ArrayList 的本质1.1.1 底层数据结构JDK 1.7

Java Map排序如何按照值按照键排序

《JavaMap排序如何按照值按照键排序》该文章主要介绍Java中三种Map(HashMap、LinkedHashMap、TreeMap)的默认排序行为及实现按键排序和按值排序的方法,每种方法结合实... 目录一、先理清 3 种 Map 的默认排序行为二、按「键」排序的实现方式1. 方式 1:用 TreeM

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

MySQL数据库双机热备的配置方法详解

《MySQL数据库双机热备的配置方法详解》在企业级应用中,数据库的高可用性和数据的安全性是至关重要的,MySQL作为最流行的开源关系型数据库管理系统之一,提供了多种方式来实现高可用性,其中双机热备(M... 目录1. 环境准备1.1 安装mysql1.2 配置MySQL1.2.1 主服务器配置1.2.2 从

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代