Reprint Please specify the Source:Jiq ' s technical Blog
RPC , the remote procedure call. is to invoke the method on the remote machine.
The principle is actually very simple, that is, the program running on the client when the object method is called, the underlying call to the method is converted to tcp/http request, send to remote server, remote server listens to fixed port, receive this tcp/http after the request, the relevant information is resolved, including which method the client wants to invoke, what the parameters are, and then make the corresponding call, and then send the result back through the packet.
RPC in general there will be a "contract" concept, that is, the client and the server side of the mutually agreed interface, indicating which interfaces the server implements, the client can use these interfaces. The following is an example of a simple RPC framework that I implemented .
First, the client
The client typically creates a service access Proxy, which is actually an object of the contract interface type, and here is an example of creating a service proxy:
Create proxy, invoke service Ihelloservice proxy= (ihelloservice) rpcproxyfactory.createproxy (Ihelloservice.class, "HelloService", 3000); SYSTEM.OUT.PRINTLN ("Service invocation Result:" +proxy.sayhello ("Jiyichin"));
which Createproxy the implementation of the interface is as follows:
/** * Create Remote Call proxy * @paramobjClass Interface Class object * @paramserviceName service name * @paramURL service address * @paramtimeout Connection Timeout period * @ return * @throws Exception */publicstatic Object createproxy (class<?> objclass, String serviceName, stringurl, int t Imeout) throws exception{//Parse call address String[]urls = Url.split (":"); stringipaddress = Urls[1];intport =integer.parseint (urls[2]); Create Invocationhandlercbipinvocationhandlerhandler = new Cbipinvocationhandler (ipAddress, port, timeout); Handler.setservicename (ServiceName); Returns Agent Returnproxy.newproxyinstance (Thread.CurrentThread (). Getcontextclassloader (), New Class[]{objclass}, Handler );}
Obviously you can see that with the help of Span lang= "en-US" style= "Font-family:calibri" >javainvocationhandler
dynamic proxy mechanism, through proxy static method newproxyinstance Return to the service proxy.
which Cbipinvocationhandler is the core of the client code, is the implementation of the Invocationhandler interface of Java dynamic agents, which Invoke The method is implemented as follows:
/** * All method calls are executed via Invoke */publicobject Invoke (Object Proxy, method, object[] args) throws Throwable{objectresult = null;try{//Gets the call related information stringbeanname = This.servicename;//this.targrtobject.getclass (). Getsimplename (); Stringmethodname = Method.getname (); String[]argtypes = Createparamsignature (Method.getparametertypes ()); Initiates a remote method synchronous call, passing the invocation information result = Invokesync (Beanname,methodname, argtypes, args);} catch (Exceptionee) { ee.printstacktrace (); returnnull;} Returnresult;}
The function of the Invokesync method is to invoke relevant information through the Mina Framework (Javanio Framework, asynchronous event-driven, providing tcp/udp high-level abstraction of communication API ) sent out.
Second, the service side
through Mina the framework implements a service-side program that obtains request packets from a method call from the client and resolves the call-related information.
/** * received a message from the client */@Override public void messagereceived (iosessionsession, Object message) throws Exception {if (message instanceofcbiptcprequest) {cbiptcprequestrequest = (cbiptcpreq uest) message; try {//Read the spring configuration file to get the service fully qualified name based on the service name and then reflect the target instance Applicationcont Extctx = new Classpathxmlapplicationcontext ("Dsf_config.xml"); Serviceconfigservice = (serviceconfig) Ctx.getbean (Request.getbeanname ()); Class<?>objclass = Class.forName (Service.getservicename ()); Objectobj = Objclass.newinstance (); Invokes the specified method Cbipskeletonskeleton = new Cbipskeleton (obj, Obj.getclass ()); Objectresult = Skeleton.invoke (Request.getmethodname (), Request.getargs ()); Reply Cbiptcpresponse response= new Cbiptcpresponse (); Response.setrequestid (Request.getid ()); Request ID Response.setbeanname (Request.getbeanname ()); Response.setmethodname (Request.getmethodname ()); Response.setresult (result); Session.write (response); Similar socket}catch (Exceptionee) {ee.printstacktrace (); } } }
This packet receive function is mainly three steps:
( 1 to know which class to call through the received client request, read the fully qualified name of the class from the configuration file loaded into the JVM , reflecting the class instance;
( 2 ) The method call is made by the reflected instance;
( 3 ) by Mina The framework returns the result of the call;
Java Fundamentals: Dynamic proxy application in RPC framework