0
点赞
收藏
分享

微信扫一扫

实现RPC功能原来只需要一个类

岛上码农 2021-09-25 阅读 26
日记本

前言:最近在研究dubbo,翻到dubbo作者梁飞11年发在iteye上面的一篇文章https://javatar.iteye.com/blog/1123915
只用了一个类RpcFramework,加上注释大概百行代码,就实现了一个简单的RPC框架。
详细代码可以见原文。
RpcFramework里面就两个方法,一个方法用于provider端,进行服务暴露;一个方法用于consumer端,引入服务;
先看服务是如何暴露的。

/**
     * 暴露服务
     *
     * @param service 服务实现
     * @param port 服务端口
     * @throws Exception
     */
    public static void export(final Object service, int port) throws Exception {
        if(service == null){
            throw new IllegalArgumentException("service instance == null");
        }
        if(port <= 0 || port > 65535){
            throw new IllegalArgumentException("Invalid port " + port);
        }
        System.out.println("Export service " + service.getClass().getName() + " on port " + port);
        //监听一个socket端口
        ServerSocket server = new ServerSocket(port);
        for(;;) {
            try {
                //如果有新的socket连接,开启一个新的线程进行处理
                final Socket socket = server.accept();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            try {
                                ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
                                try {
                                    //从输入流中读取方法名,参数等
                                    String methodName = input.readUTF();
                                    Class<?>[] parameterTypes = (Class<?>[])input.readObject();
                                    Object[] arguments = (Object[])input.readObject();
                                    ObjectOutputStream output = new ObjectOutputStream(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 e) {
                e.printStackTrace();
            }
        }
    }

服务暴露方法的主要逻辑
1.初始化一个SocketServer,有新连接过来开启新线程进行处理
2.线程具体逻辑:
从socket中读取consumer发过来的methodName,param等信息;
反射调用目标method;
将结果写回socket发给cosumer;

再看cosumer端是如何引用服务的

/**
     * 引用服务
     *
     * @param <T> 接口泛型
     * @param interfaceClass 接口类型
     * @param host 服务器主机名
     * @param port 服务器端口
     * @return 远程服务
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {
        if(interfaceClass == null){
            throw new IllegalArgumentException("Interface class == null");
        }
        if(! interfaceClass.isInterface()){
            throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");
        }
        if (host == null || host.length() == 0){
            throw new IllegalArgumentException("Host == null!");
        }
        if (port <= 0 || port > 65535){
            throw new IllegalArgumentException("Invalid port " + port);
        }
        System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":" + port);
        //创建一个接口代理
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
                //新建一个socket连接
                Socket socket = new Socket(host, port);
                try {
                    ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                    try {
                        //将method,param等以ObjectOutputStream的形式写入socket
                        output.writeUTF(method.getName());
                        output.writeObject(method.getParameterTypes());
                        output.writeObject(arguments);
                        ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
                        try {
                            //读取对象
                            Object result = input.readObject();
                            if (result instanceof Throwable) {
                                throw (Throwable) result;
                            }
                            return result;
                        } finally {
                            input.close();
                        }
                    } finally {
                        output.close();
                    }
                } finally {
                    socket.close();
                }
            }
        });
    }

服务引用的逻辑也比较清楚。
1.对接口创建jdk代理。
2.代理逻辑:
新建socket连接;
将method,param等以ObjectOutputStream形式写入socket发给provider;
读取返回的结果;

总结:就一个类,实现了一个基于BIO的RPC功能,包含了最基础的服务导出,服务引入,对象序列化,网络传输等功能。其实dubbo最核心的无非也就是这几个功能,后面我会抽时间继续学习dubbo是如何提供这几个功能的。虽然只是一个简单的例子,但是其中的参数校验、代码的优雅,涉及的基础知识点,有太多值得我们学习的点,比较遗憾的是梁飞已于近日离开阿里,后续只能通过内网的各种帖子或文章来膜拜大神了。

举报

相关推荐

0 条评论