手写一个简单的RPC框架

        随着soa的出现和普及,远程分布式调用已经成为主流。逐渐流行起来的微服务更是让RPC大放异彩。目前业界开源的RPC框架非常多,比较主流的RPC框架有facebook开发的Apache Thrift,Hadoop的Avro-RPC,google开源的gRpc等。dubbo也是基于RPC框架之上的一个服务治理框架。

        下面将通过java原生的序列化,Socket通信,动态代理和反射机制,实现一个简单的RPC框架。

        它主要由三部分组成:

1、服务提供者:运行在服务端,负责提供服务接口定义和服务实现类。

2、服务发布者:它运行在RPC服务端,负责将本地服务发布成远程服务,供其他消费者调用。

3、本地服务代理:它运行在RPC客户端,通过代理调用远程服务提供者,然后将结果进行封装返回给本地消费者。

        首先是服务端接口定义和实现:

public interface EchoService {

        String echo(String ping);

}

public class EchoServiceImpl implements EchoService{

    @Override

    public String echo(String ping) {

        return ping!=null?ping +" I am Ok":" I am Ok";

    }

}

服务端的服务发布者代码如下:

public class RpcExporter {

        static Executor executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        public static void exporter(String hostName , int port) throws Exception{

                ServerSocket server = new ServerSocket();

                server.bind(new InetSocketAddress(hostName, port));

                try{

                        while(true){

                            executor.execute(new ExporterTask(server.accept()));

                        }

                }catch(Exception e){

                    e.printStackTrace();

                }

        }

        private static class ExporterTask implements Runnable{

            Socket client = null ;

            public ExporterTask(Socket client){

            this.client = client;

            }

            @Override

            public void run(){

                    ObjectInputStream input = null ;

                    ObjectOutputStream out = null;

                try{

                    //从client获取数据

                    input = new ObjectInputStream(client.getInputStream());

                    String interfaceName = input.readUTF();

                    Class service = Class.forName(interfaceName);

                    String methodName = input.readUTF();

                    Class[] parameterTypes = (Class[])input.readObject();

                    Object[] arguments = (Object[] )input.readObject();

                    Method method = service.getMethod(methodName, parameterTypes);

                    Object result = method.invoke(service.newInstance(), arguments);

                    out = new ObjectOutputStream(client.getOutputStream());

                    out.writeObject(result);

                }catch(Exception e){

                    e.printStackTrace();

                }finally{

                        try {

                            input.close();

                            out.close();

                        } catch (IOException e) {

                            // TODO Auto-generated catch block

                            e.printStackTrace();

                        }

            }

        }

    }

}

        服务发布者的主要职责如下:

(1)作为服务端,监听客户端的TCP连接,接收新的客户端连接之后,将其封装成Task,让线程池执行。

(2)将客户端发送的码流反序列化成对象,反射调用服务实现者,获取执行结果。

(3)将执行结果对象反序列化,通过Socket发送给客户端。

(4)远程服务调用完成之后,释放socket等连接资源,防止句柄泄露。

        接下来是客户端本地服务代理源码:

public class RpcImporter {

        @SuppressWarnings("unchecked")

        public S importer(final Class serviceClass , final InetSocketAddress addr){

            return (S)Proxy.newProxyInstance(serviceClass.getClassLoader(), new Class[]{

            serviceClass.getInterfaces()[0]}, new InvocationHandler() {

                    Socket socket = null ;

                    ObjectOutputStream output = null ;

                    ObjectInputStream input = null ;

                    @Override

                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                         try{

                                socket = new Socket();

                                socket.connect(addr);

                                output = new ObjectOutputStream(socket.getOutputStream());

                                output.writeUTF(serviceClass.getName());

                                output.writeUTF(method.getName());

                                output.writeObject(method.getParameterTypes());

                                output.writeObject(args);

                                input = new ObjectInputStream(socket.getInputStream());

                                return input.readObject();

                        }finally{

                            if(output!=null){

                                output.close();

                            }

                            if(input!=null){

                                input.close();

                            }

                    }

                }

         });

     }

}

        本地服务代理的主要功能如下:

(1)将本地的接口调用转化为JDK的动态代理,在动态代理中实现接口的远程调用。

(2)创建Socket客户端,根据指定地址连接远程服务提供者。

(3)同步阻塞等待服务端返回应答,回去应答之后返回。

        下面是测试代码:

public class RpcTest {

        public static void main(String[] args){

            //启动服务端 轮询接受客户端的请求

            new Thread(new Runnable(){

                @Override

                public void run() {

                    try{

                        RpcExporter.exporter("127.0.0.1", 8080);

                    }catch(Exception e){

                        e.printStackTrace();

                    }

             }

            }).start();

            RpcImporter importer = new RpcImporter();

            EchoService echo = importer.importer(EchoServiceImpl.class, new InetSocketAddress("localhost",8080));

            System.out.println(echo.echo("are you ok ? "));

        }

}

        首先,创建一个异步发布服务端的线程并启动,用于接收RPC客户端的请求,根据请求参数调用服务实现类,返回结果给客户端。随后,创建客户端服务代理类,构造RPC请求参数,发起RPC调用,将调用结果输出到控制台。执行结果如下所示:

        are you ok ? I am Ok

你可能感兴趣的:(手写一个简单的RPC框架)