What is proxy mode?Summary of proxy mode module

Keywords: Programming JDK Java jvm

Hello, this is a blog to keep learning for your dreams.This is the first article to share my understanding of Agent Mode. The style of the article will always be told in a question and answer way, which is one of my personal favorites and is equivalent to a simulated interview.(

What is an agent?

Let's imagine a scenario where a French winery wants to sell alcohol and expand its business in mainland China.But the winery just wanted to provide wine, other sales, shipping and so on. They didn't want to do that, so they found an agent in China.Agents are responsible for doing things that the original winery did not want to do, and the winery only needs to provide wine, which completes a business expansion, which is also the meaning of the existence of agents. Design comes from life, based on the above scenarios, we can know the application scenario of agent mode, and the working module of agent mode.

  • Scenario: Used for the increase and expansion of the native function, alcohol sale.
  • Work module: divided into agents - winery, and agents - agent agencies in China.

How many proxies are there in Java?

It can be divided into static proxy and dynamic proxy.
Static proxies are primarily designed to implement extended functionality by manually writing proxy classes when writing code. They are called static because all proxy relationships are fixed.As in the above scenario, A Winery has created an agent department that only goes to act for A Winery's business, called A Agent, and their relationship is one-to-one fixed.
The biggest change of dynamic proxy over static proxy is that you don't need to implement your own proxy class manually, you only need to get one through JDK or CGLIB, and the proxy class is generated and loaded at runtime.Returning to the above scenario, Dynamic Agent is equivalent to A finding an agency, which has brought an agent A$Proxy for Factory A. When A's wine has arrived, it will be better to hand it over directly to A$Proxy for operation.At this time, B Winery also needs to find an agent, or an agency, which assigns B$Proxy as an agent for B Winery.In the above scenarios, an agent is often referred to as a JDK dynamic proxy or CGLIB.

How is a static proxy implemented?Do a good or bad analysis?

The premise of proxy implementation is how to get calls to the original interface.So there are two ways to do this: combining and inheriting.

  • Combination: Implements the same interface as the proxy class, then passes a reference to the proxy class to call the target function.
  • Inheritance: Inherit the proxy class, override the target function, and then call the target function through super. Actually, both static proxy and static proxy are implemented based on these two methods. The specific operation of static proxy can be achieved by writing corresponding proxy classes for the classes that need proxy in these two ways.The code is as follows:
// Combination: Inherits the same interface and passes in a reference to the proxy class.
public class Car3 implements MoveAble {
	private Car c;//Proxy Class
	public Car3(Car c) {
		this.c = c;
	}
	@Override
	public void move() {
		long begin = System.currentTimeMillis();
		System.out.println("car start");
		c.move();//Call the target function by reference
		long end = System.currentTimeMillis();
		System.out.println("car stop,time:" + (end - begin));
	}
}

//Inheritance: Inherit the proxy class, override the target function, and then call the target function through super.
public class Car2 extends Car {
	@Override
	public void move() {// Override objective function
		long begin = System.currentTimeMillis();
		System.out.println("car start");
		super.move();
		long end = System.currentTimeMillis();
		System.out.println("car stop,time:" + (end - begin));
	}
}
  • Advantages: The proxy has a clear relationship with the proxy class, and is easy to read and debug.
  • Disadvantages: Manually writing proxy implementations is cumbersome and inflexible, and writing one proxy class per class can result in too many proxy classes.

How is dynamic proxy implemented?Do a good or bad analysis?

Once you understand the static proxy principle above, the dynamic proxy principle is well understood.Dynamic proxy is the process of manually writing proxies to implement them by the framework itself, then loading and running them.How does the framework work?We know that the code becomes a.Java file, compiles it into a.Class file, and eventually loads it into the JVM to become a class.The framework is to help us generate the java/class file corresponding to the proxy class at runtime, then load the JVM into a class, and finally reflect to create the corresponding proxy object and return it to us for use.If you are interested in the process of generating the file, you can see the Muchow Web video link at the end of the article.The corresponding usage code for the dynamic proxy is as follows:

// JDK Dynamic Proxy Test Function
public static void main(String[] args) {
	Car c = new Car();
	InvocationHandler h = new Handler(c);
	
	// This must be returned with the MoveAble interface, otherwise an error will be reported
	MoveAble c1 = (MoveAble) Proxy.newProxyInstance(c.getClass().getClassLoader(), c.getClass().getInterfaces(), h);
	c1.move();
	/**
	 * In summary, the target class of the JDK dynamic proxy needs to implement the interface because the corresponding subclass needs to be implemented.
	 * The other core is the invoke function inside InvocationHandler, which makes use of combinations to implement method calls.
	 */
	}

    // Core handler class
public class Handler implements InvocationHandler{
	
	/**
	 * Object to be proxied
	 */
	private Object obj;

	public Handler(Object obj) {
		super();
		this.obj = obj;
	}

	/**
	 * proxy: Proxy Object
	 * method: Proxy functions
	 * args: List of parameters for a function
	 * 
	 * Return: Object method return value
	 */
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		
		long begin = System.currentTimeMillis();
		System.out.println("car start");
		method.invoke(obj, args);
		long end = System.currentTimeMillis();
		System.out.println("car stop,time:" + (end - begin));
		return null;
	}

}
    // CGLIB Dynamic Proxy Test Function
public static void main(String[] args) {
	Train t = new Train();
	CglibHandler cg = new CglibHandler();
	Train tx = (Train) cg.getProxy(t.getClass());
	tx.move();
	
	/**
	 * To sum up: cglib is a dynamic proxy implemented by inheritance.So you can do it without an interface.
	 * His core interface is MethodInterceptor, which intercepts all functions of the parent class and then enhances them by calling methods of the subclasses.
	 * 
	 * Two implementations of dynamic proxy correspond to the implementation of static proxy
	 * JDK Dynamic Proxy: Composite
	 * CGLIB Dynamic proxy: Inheritance.
	 */
}
    
    // Core handler class
public class CglibHandler implements MethodInterceptor{
	private Enhancer enhance = new Enhancer();
	public Object getProxy(Class<?> clazz){
		// Create subclasses of incoming classes
		enhance.setSuperclass(clazz);
		// Call back to yourself when you finish creating
		enhance.setCallback(this);
		return enhance.create();
	}

	/**
	 * obj:Proxy Class
	 * m: Proxy function
	 * args: parameter list
	 * proxy: Proxy class instance
	 * 
	 * Return value Object: Method return value
	 */
	@Override
	public Object intercept(Object obj, Method m, Object[] args, MethodProxy proxy) throws Throwable {
		
		long begin = System.currentTimeMillis();
		System.out.println("train start");
		// Execute that function of the parent class
		proxy.invokeSuper(obj, args);
		long end = System.currentTimeMillis();
		System.out.println("train stop,time:" + (end - begin));
		return null;
	}

}  
  • Advantages: Flexible and easy to use, no need to manually create proxy classes.
  • Disadvantages: Frequent creation of proxy classes may cause insufficient metaspace to trigger frequent FullGC, so if we need to use dynamic proxies on our own, we will generally cache the created proxy objects for reuse.

Reference books and links: <Secret of Mode - Agent Mode>

Posted by jasonok6 on Sun, 01 Mar 2020 18:44:42 -0800