RPC原理与实例

什么是RPC? RPC是Remote Procedure
Call的缩写,像Client-Servier一样的远程过程调用,也就是调用远程服务就跟调用本地服务一样方便,一般用于将程序部署在不同的机器上,供客户端进行调用。就像一个request-response调用系统一样简单。在面向对象编程的程序中,RPC也可以用Remote
method
invocation(RMI)来展现。为什么用它呢,因为随着分布式结构的普遍,越来越多的应用需要解耦,将不同的独立功能部署发布成不同的服务供调用。
  
**

它的主要流程是Client -> Client Stub -> Network -> Server Stub -> Server

执行完成之后再进行返回。   这里边比较重要的就是Clint Stub和Server
Stub,他们主要的作用就是将调用的方法和参数进行编码(Marshalling)序列化,将序列化后的数据通过网络发送给Server
Stub,然后等待Server回执。Server
Stub将受到的序列化字节进行解码(Unmarshaling)反序列化,然后再将参数传入到对应到的方法中执行,将得出的结果计算出来之后再进行返回,返回的过程和正向的过程类似。

这里写图片描述

通过RPC原理实现类的远程调用

client:

```
    public class RpcImporter<S> {
    @SuppressWarnings("unchecked")
    public S importer(final Class<?> serviceClass,final InetSocketAddress addr){
        return  (S) Proxy.newProxyInstance(
                serviceClass.getClassLoader(),//classloader
                new Class<?>[] {serviceClass.getInterfaces()[0]},//目标类接口 
                //代理类对象
                new InvocationHandler(){
                    @Override
                    public Object invoke(Object proxy, Method method,
                            Object[] args) throws Throwable {
                        Socket socket =null;
                        ObjectOutputStream output =null;
                        ObjectInputStream input=null;       
                    try{
                        socket=new Socket();
                        socket.connect(addr);   
                        //client数据序列化输出
                        output =new ObjectOutputStream(socket.getOutputStream());
                        output.writeUTF(serviceClass.getName());//className
                        output.writeUTF(method.getName());//methodname
                        output.writeObject(method.getParameterTypes());//param name
                        output.writeObject(args);
                        //接收数据
                        input =new ObjectInputStream(socket.getInputStream());
                        return input.readObject();
                    }finally{
                            if(socket != null)
                                socket.close();
                            if(output !=null)
                                output.close();
                            if(input !=null)
                                input.close();
                    }
            }
        });
    }
}

Service

public class RpcExporter {
    //获取cpu核心数
    static Executor executor =Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    //server
    public static void exporter(String hostName,int port) throws IOException{
        ServerSocket server=new ServerSocket();
        server.bind(new InetSocketAddress(hostName,port));
        try {
            while(true){
                executor.execute(new ExporterTask(server.accept()));
            }
        }finally{
            server.close();
        }
    }   
    private static class ExporterTask implements Runnable{      
        Socket client =null;
        public ExporterTask(Socket client){
            this.client=client;
        }
        @Override
        public void run() {
            ObjectInputStream input=null;
            ObjectOutputStream output=null;
        try {
            //反序列化
            input =new ObjectInputStream(client.getInputStream());
            String interfaceName=input.readUTF();   
            Class<?> service=Class.forName(interfaceName);
            //method name
            String methodName=input.readUTF();
            //parameter type and argument
            Class<?>[] parameterTypes=(Class<?>[])input.readObject();
            Object[] arguments=(Object[])input.readObject();
            //method
            Method method =service.getMethod(methodName, parameterTypes);
            //execute method
            Object result=method.invoke(service.newInstance(), arguments);      
            //执行结果,序列化后返回到客户端
            output =new ObjectOutputStream(client.getOutputStream());
            output.writeObject(result);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(output !=null)
                try{
                    output.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
                if(input !=null)
                    try{
                        input.close();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                    if(client !=null)
                        try{
                            client.close();
                        }catch(IOException e){
                            e.printStackTrace();
                        }
            }   
        }
    }
}

调用的接口与实现的类:

    public interface  EchoService {
    String echo(String ping);
    String addclient(String clientno);
    String deleteclient(String clientno);
    String editclient(String clientno);
    String selectclient(String clientno);
    String pagelist(String clientno);
}
public class EchoServiceImpl implements EchoService{
    @Override
    public String echo(String ping) {       
        return ping !=null ? ping + "--> I am ok." : " I am ko.";
    }   
    @Override
    public String addclient(String clientno) {
        return clientno !=null ? clientno + "addclient" : "is null";
    }
    @Override
    public String deleteclient(String clientno) {
        // TODO Auto-generated method stub
        return clientno !=null ? clientno + "deleteclient." : " I am ko.";
    }
    @Override
    public String editclient(String clientno) {
        // TODO Auto-generated method stub
        return clientno !=null ? clientno + "editclient." : " I am ko.";
    }
    @Override
    public String pagelist(String clientno) {
        // TODO Auto-generated method stub
        return clientno !=null ? clientno + "pagelist." : " I am ko.";
    }
    @Override
    public String selectclient(String clientno) {
        // TODO Auto-generated method stub
        return clientno !=null ? clientno + "selectclient." : " I am ko.";
    }
}

测试:

    public class Test {
    public static void main(String[] args) throws Exception{
        //服务端
        new Thread (new Runnable(){
            public void run(){
                try{
                    RpcExporter.exporter("localhost", 8088);
                }catch(Exception e){
                    e.printStackTrace();            
                }
            }
        }).start();
        //客户端
        RpcImporter<EchoService> importer=new RpcImporter<EchoService>();
        //传入类与ip地址,返回代理
        EchoService echo=importer.importer(EchoServiceImpl.class, new InetSocketAddress("localhost",8088));

        System.out.println(Runtime.getRuntime().availableProcessors());         
        System.out.println(echo.echo("Are you ok?"));
    }
}

猜你喜欢

转载自blog.csdn.net/linkingfei/article/details/81505543
今日推荐