A simple RPC instance (Java)

Source: Internet
Author: User

Come to Ali LIANGF: If offended, please forgive

Rpcframework:

 PackageCom.sunchao.demo;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy;ImportJava.net.ServerSocket;ImportJava.net.Socket;/*** rpcframework * Copy from the Alibaba LIANGF * *@authorAdministrator **/ Public classRpcframework {/**Exposure Service * *@paramService *@paramPort *@throwsIOException*/     Public Static voidExportFinalObject Service,intPortthrowsioexception{if(Service = =NULL)            Throw NewIllegalArgumentException ("service instance = = NULL"); if(Port <= 0 | | port > 65535)            Throw NewIllegalArgumentException ("Invard port" +port); System.out.println ("Export Service" + Service.getclass (). GetName () + "on port" +port); @SuppressWarnings ("Resource") ServerSocket Server=NewServerSocket (port);  for(;;) {            Try{                 FinalSocket socket =server.accept (); NewThread (NewRunnable () {@Override Public voidrun () {Try{                             Try{ObjectInputStream input=NewObjectInputStream (Socket.getinputstream ()); Try{String MethodName=Input.readutf (); //method Parameter TypeClass<?>[] Parametertypes = (class<?>[]) input.readobject (); //method Parameterobject[] arguments =(object[]) input.readobject (); ObjectOutputStream Output=NewObjectOutputStream (Socket.getoutputstream ()); Try{Method Method=Service.getclass (). GetMethod (MethodName, parametertypes); Object result=Method.invoke (service, arguments);                                Output.writeobject (result); }Catch(Throwable t) {output.writeobject (t); }finally{output.close (); }                            }finally{input.close (); }                         }finally{socket.close (); }                    }Catch(Exception e) {e.printstacktrace ();            }}). Start (); } Catch(Exception E1) {e1.printstacktrace (); }        }    }      /*** Reference Service * *@paramInterfaceclass Interface Type *@paramhost hostname *@paramPort Port Number *@returnRemote Service*/@SuppressWarnings ("Unchecked")     Public Static<T> T Refer (FinalClass<t> Interfaceclass,FinalString Host,Final intPort) {        if(Interfaceclass = =NULL)            Throw NewIllegalArgumentException ("Interface class = = NULL"); if(!interfaceclass.isinterface ())Throw NewIllegalArgumentException ("The" + interfaceclass.getname () + "must Be Interface class"); if(Host = =NULL|| Host.length () = = 0)            Throw NewIllegalArgumentException ("host = = NULL"); if(Port <= 0 | | port > 65535)            Throw NewIllegalArgumentException ("Invalid port" +port); System.out.println ("Get remote Service" + interfaceclass.getname () + "from service" + Host + ":" +port); return(T) Proxy.newproxyinstance (Interfaceclass.getclassloader (),NewClass<?>[]{interfaceclass},NewInvocationhandler () {@Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsthrowable {Socket Socket=NewSocket (Host,port); Try{objectoutputstream output=NewObjectOutputStream (Socket.getoutputstream ()); Try{Output.writeutf (Method.getname ());                        Output.writeobject (Method.getparametertypes ());                        Output.writeobject (args); ObjectInputStream input=NewObjectInputStream (Socket.getinputstream ()); Try{Object result=Input.readobject (); if(Resultinstanceofthrowable)Throw(throwable) result; returnresult; }finally{input.close (); }                    }finally{output.close (); }                }finally{socket.close ();    }                            }        }); }}

Service Interface:

 Package Com.sunchao.demo; /** * Service Interface *   @author  */Publicinterface  helloservice {    string hello (string name);}

Service implementations:

 Package Com.sunchao.demo;  Public class Implements HelloService {    @Override    public  string Hello (string name) {                return "Hello" + name;}    }

Server-side service startup:

 PackageCom.sunchao.demo;Importjava.io.IOException;/*** Burst Service * *@authorAdministrator **/ Public classRpcprovider { Public Static voidMain (String args[])throwsioexception{HelloService Service=NewHelloserviceimpl (); Rpcframework.export (Service,1234); }}

Client Service Proxy:

 PackageCom.sunchao.demo;/*** Customer * *@authorAdministrator **/ Public classRpcconsumer { Public Static voidMain (String args[])throwsinterruptedexception{HelloService Service=Rpcframework.refer (HelloService.class, "10.1.58.54", 1234);  for(inti = 0; i < Integer.max_value; i++) {String Hello= Service.hello ("World" +i);            System.out.println (hello); Thread.Sleep (1000); }            }}

A simple RPC instance (Java)

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.