手写RPC从零开始

  前言:现在随着微服务、分布式的流行,基本大点的项目必用RPC框架,比如阿里的dubbo,Thrift等,现在我将一步步来手写rpc,我们来慢慢熟悉这个过程,也便于看dubbo的源码,不过在这之间肯定也会遇到很多问题,希望可以和大家一起共同解决。

 一:rpc的基本组成

 二:rpc的工作原理

 2.1、注册客户端服务

2.2、开启rpc服务端

2.3、客户端以本地的方式来调用服务端

2.4、客户端代理找到服务端地址,连接服务端,然后将参数、方法等通过发送给服务端

2.5、服务端接收请求后将数据进行解码,然后根据解码的信息来执行本地程序,并将执行的结果返回给客户端

2.6、客户端进行解码获取返回的结果

三:编码

3.1、服务端

复制代码
 /**
     * 启动rpc服务
     * @throws IOException
     */
    void start() throws IOException;

    /**
     * 服务注册
     * @param serviceInterface 服务接口
     * @param impl 服务实现类
     */
    void register(Class serviceInterface, Class impl);
服务端接口
复制代码
复制代码
@Override
    public void start() throws IOException {
        ServerSocket server = new ServerSocket();
        server.bind(new InetSocketAddress(port));
        System.out.println("Bio rpc 服务启动开始###端口###" + port);
        try {
            while (true) {
                System.out.println("等待客户端接入");
                executor.execute(new ServersTask(server.accept()));
            }
        } catch (Exception e) {
            if (server != null) {
                server.close();
            }
        }
    }

    @Override
    public void register(Class serviceInterface, Class impl) {
        serviceRegistry.put(serviceInterface.getName(), impl);
    }

    static class ServersTask implements Runnable {
        Socket client = null;

        public ServersTask(Socket socket) {
            this.client = socket;
        }

        ObjectInputStream input = null;//输入流
        ObjectOutputStream output = null;//输出流

        @Override
        public void run() {
            //接收客户端发送来的字节流,并转化成对象,反射调用服务实现者,获取执行结果
            try {
                input = new ObjectInputStream(this.client.getInputStream());
                String interfaceName = input.readUTF();
                String methodName = input.readUTF();
                Class<?>[] parameterType = (Class<?>[]) input.readObject();
                Object[] args = (Object[]) input.readObject();
                Class serverClass = serviceRegistry.get(interfaceName);
                if (serverClass == null) {
                    throw new ClassNotFoundException(interfaceName + " not found");
                }
                Method method = serverClass.getMethod(methodName, parameterType);
                Object result = method.invoke(serverClass.newInstance(), args);
                //执行结果反序列化返回给客户端
                output = new ObjectOutputStream(this.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 (this.client != null) {
                    try {
                        this.client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
服务端的实现
复制代码

 3.2、客户端代理

 我们需要一个代理类来生成需要的接口

复制代码
 public static <T> T create(final Class<?> serviceInterface, final String ip, final int port) {
        //将本地的接口调用转换成JDK的动态代理,在动态代理中实现接口的远程调用
        return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class<?>[]{serviceInterface}, new ProxyHandler(ip, port, serviceInterface));
    }

    static class ProxyHandler implements InvocationHandler {
        private String ip;
        private int port;
        private Class<?> serviceInterface;

        public ProxyHandler(String ip, int port, Class<?> serviceInterface) {
            this.ip = ip;
            this.port = port;
            this.serviceInterface = serviceInterface;
        }
代理
复制代码

在invoke中我们需要将参数,方法名等传入到服务端,然后等待返回服务端的结果

复制代码
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Socket socket = null;
            ObjectOutputStream output = null;
            ObjectInputStream input = null;
            try {
                // 创建Socket客户端,根据指定地址连接远程服务提供者
                socket = new Socket(ip, port);
                // 将远程服务调用所需的接口类、方法名、参数列表等编码后发送给服务提供者
                output = new ObjectOutputStream(socket.getOutputStream());
                output.writeUTF(serviceInterface.getName());
                output.writeUTF(method.getName());
                output.writeObject(method.getParameterTypes());
                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();
                }
            }
连接服务端
复制代码

上面就是服务端的相关代码,现在我们来看下写下客户端的调用

复制代码
long start =System.currentTimeMillis();
        for (int i=0;i<200;i++){
            try {
                IOrderService orderService= ProxyFactory.create(IOrderService.class,"127.0.0.1",8088);
                System.out.println(orderService.getOrderDtoByUserId(i));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        long end=System.currentTimeMillis();
        System.out.println("总耗时:"+(end-start));
客户端调用
复制代码

运行结果

四:总结

我们采用的是BIO的传输方式,必须需要执行完毕一个请求后才可以执行下一个请求,这样就会导致效率很低,采用线程池可以解决这个问题,但是如果请求非常多,依然会出现堵塞,随意下一篇主要写采用netty的方式来实现rpc

下载地址

 

posted @   朝向远方  阅读(2308)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示