Java Fundamentals: Dynamic proxy application in RPC framework

Source: Internet
Author: User

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 easy. is the program executed on the client when calling the object method, the underlying call to the method is converted to a tcp/http request, sent to the remote server, remote server listening to the fixed port, received this The tcp/http request will parse out the relevant information, including which method the client wants to invoke, what the parameter is, and then make the appropriate call to send the result back to the packet.

RPC There is usually a "contract" concept. That is, the client and the server two-party 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 a sample to create 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"));

among 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 );}

It is very obvious to see the use of Javainvocationhandler dynamic agent mechanism. newproxyinstance returns the service proxy via proxy static method .


among Cbipinvocationhandler is the core of the client code. Is a Java Dynamic Agent that implements the invocationhandler interface , with the invoke method implementation such as the following:

/** * All method calls are run through 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 gets the request packets from the client's method call. Resolves the call-related information.

/** * Receive Message from client */@Override public void messagereceived (iosessionsession, Object message) throws Except Ion {if (message instanceofcbiptcprequest) {cbiptcprequestrequest = (cbiptcp                                                         Request) message; try {//Read the spring configuration file to get the service fully qualified name from 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 sockets}catch (Exceptionee) {ee.printstacktrace (); } } }


This packet receive function is mainly three steps:

( 1 The client request that is received knows which class to call, and the fully qualified name of the class is read 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.