Java agent probe technology

1. Basic concepts

AOP static proxy : AOP's static proxy mainly enhances the target object by changing the bytecode of the target object when the virtual machine is started. It is more efficient than dynamic proxy.
Java agent : Java agent can usually be understood as a "plug-in", which is essentially a well-provided jar file in which we carefully code the operations that need to be performed. These operations are used for Java applications through the API provided by the java.lang.Instrument package The Instrument of the program, for example, can dynamically add statistics on the execution time before and after the method is executed.
java.lang.instrument : Tool API for equipping Java applications provided after JDK1.5, allowing JavaAgent program Instrument (equipment) to run on JVM applications. The usual practice is to provide methods for use in bytecode Insert additional code to be executed. Two implementations are provided after JDK1.6: the command line (-javaagent) form is processed before the application is started (premain mode); it is processed at a certain time after the application is started (agentmain).
ClassFileTransformer : JavaAgent's code needs to provide an implementation class for custom bytecode conversion.
Javaassist : It is a class library for processing Java bytecode. Can allow to define the class while the Java program is running, and can modify the class file when the JVM loads the class.

flow chart:
Insert picture description here

2. Application scenarios

Pinpoint distributed link
SkyWalking distributed link

3. Implementation steps
  • Define a resources/META-INF/MANIFEST.MF file and add premain-class configuration items in it.
  • Create the class specified by the premain-class configuration item and implement the premain() method in it. The method signature is as follows:
public static void premain(String agentArgs, Instrumentation inst){
    
    
   ... 
}
  • Package the MANIFEST.MF file and the class specified by premain-class into a jar package.
  • Use -javaagent to specify the path of the jar package to execute the premain() method.
4. Small case

1) Create an agent jar
github: https://github.com/fomeiherz/agent-example
jar packaging: After the mvn clean package is
packaged, an agent.jar will be generated under {base}/target, and the meeting will be launched later Used.

2) Create test class
Create file in any local directory: App.java

public class App {
    
    
    public static void main(String[] args) {
    
    
        new App().test();
    }
    private void test() {
    
    
        System.out.println("hello agent.");
    }
}

Copy the agent.jar packaged in step 1 to the App.java file directory, and then compile and start.

Compile: javac App.java
start: java -javaagent:agent.jar App

[Reference material]
Java probe-Java Agent technology-Alibaba interview questions Java agent technology

Guess you like

Origin blog.csdn.net/fomeiherz/article/details/103221981