[TOC]
Java Remote Procedure Call Basics: A general approach to building Adaptive dynamic proxy objects Foreword
Knowledge of dynamic agents is no longer explained here. Here, how to create a dynamic proxy object that can be adapted to any interface is a common method, that is, the reference object can be any interface, for example, if the method of returning a dynamic proxy object is getProxy , and there are two interfaces at the same time UserInterface , this ProductInterface can be used:
UserInterface user = getProxy(UserInterface.class);ProductInterface product = getProxy(ProductInterface.class);
That is, no matter what the interface type is, you can use getProxy() methods to create dynamic proxy objects, and the meaning of creating such a method is very significant for building your own RPC framework, because you can actually embed the code of the remote procedure call client in the GetProxy () method. Makes a remote invocation request to the server for the purpose of the remote procedure call.
General Method GetProxy ()
The code is as follows:
@SuppressWarnings("unchecked") public static <T> T getProxy(Class<?> interfaceClass) { T proxy = (T) Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class<?>[]{interfaceClass}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); System.out.println("调用的方法名是:" + methodName); return null; } }); return proxy; }
Test
If there are two interfaces, respectively, UserInterface and ProductInterface the code is as follows:
UserInterface
package cn.xpleaf.service;public interface UserInterface { public void getUsername();}
Productinterface
package cn.xpleaf.service;public interface ProductInterface { public void getProduct();}
The test code is as follows:
@Test public void testGetProxy() { UserInterface user = getProxy(UserInterface.class); ProductInterface product = getProxy(ProductInterface.class); user.getUsername(); product.getProduct(); }
The output results are as follows:
调用的方法名是:getUsername调用的方法名是:getProduct
Practical application
Later in the development of the RPC framework will be used to fully use this common method, in the invoke method, we can embed to the server to send remote call request code, so as to achieve the purpose of remote invocation, and the underlying communication can use the socket, of course, can also be explored in front of the Netty, But for performance reasons, of course, Netty is preferred.
Java Remote Procedure Call basics: A common approach to building adaptive dynamic proxy objects