专栏首页Java架构沉思录学习一下,Dubbo创始人当年花10分钟撸的RPC骨架

学习一下,Dubbo创始人当年花10分钟撸的RPC骨架

因为要上实训课,让新同学们自行实现一个简易RPC框架,在准备PPT时,就想写个示例,发现原来一个RPC框架只要一个类,10分钟来就可以写完了,虽然简陋,也晒晒。

Java代码

/* 
 * Copyright 2011 Alibaba.com All right reserved. This software is the 
 * confidential and proprietary information of Alibaba.com ("Confidential 
 * Information"). You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement you entered 
 * into with Alibaba.com. 
 */  
package com.alibaba.study.rpc.framework;

import java.io.ObjectInputStream;  
import java.io.ObjectOutputStream;  
import java.lang.reflect.InvocationHandler;  
import java.lang.reflect.Method;  
import java.lang.reflect.Proxy;  
import java.net.ServerSocket;  
import java.net.Socket;

/** 
 * RpcFramework 
 *  
 * @author william.liangf 
 */  
public class RpcFramework {

    /** 
     * 暴露服务 
     *  
     * @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);  
        ServerSocket server = new ServerSocket(port);  
        for(;;) {  
            try {  
                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();  
            }  
        }  
    }

    /** 
     * 引用服务 
     *  
     * @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() {  
            public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {  
                Socket socket = new Socket(host, port);  
                try {  
                    ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());  
                    try {  
                        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();  
                }  
            }  
        });  
    }

}  

用起来也像模像样:

一、定义服务接口

Java代码

/* 
 * Copyright 2011 Alibaba.com All right reserved. This software is the 
 * confidential and proprietary information of Alibaba.com ("Confidential 
 * Information"). You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement you entered 
 * into with Alibaba.com. 
 */  
package com.alibaba.study.rpc.test;

/** 
 * HelloService 
 *  
 * @author william.liangf 
 */  
public interface HelloService {

    String hello(String name);

}  

(2) 实现服务

Java代码

/* 
 * Copyright 2011 Alibaba.com All right reserved. This software is the 
 * confidential and proprietary information of Alibaba.com ("Confidential 
 * Information"). You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement you entered 
 * into with Alibaba.com. 
 */  
package com.alibaba.study.rpc.test;

/** 
 * HelloServiceImpl 
 *  
 * @author william.liangf 
 */  
public class HelloServiceImpl implements HelloService {

    public String hello(String name) {  
        return "Hello " + name;  
    }

}

(3) 暴露服务

Java代码

/* 
 * Copyright 2011 Alibaba.com All right reserved. This software is the 
 * confidential and proprietary information of Alibaba.com ("Confidential 
 * Information"). You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement you entered 
 * into with Alibaba.com. 
 */  
package com.alibaba.study.rpc.test;

import com.alibaba.study.rpc.framework.RpcFramework;

/** 
 * RpcProvider 
 *  
 * @author william.liangf 
 */  
public class RpcProvider {

    public static void main(String[] args) throws Exception {  
        HelloService service = new HelloServiceImpl();  
        RpcFramework.export(service, 1234);  
    }

}

(4) 引用服务

Java代码

/* 
 * Copyright 2011 Alibaba.com All right reserved. This software is the 
 * confidential and proprietary information of Alibaba.com ("Confidential 
 * Information"). You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement you entered 
 * into with Alibaba.com. 
 */  
package com.alibaba.study.rpc.test;

import com.alibaba.study.rpc.framework.RpcFramework;

/** 
 * RpcConsumer 
 *  
 * @author william.liangf 
 */  
public class RpcConsumer {

    public static void main(String[] args) throws Exception {  
        HelloService service = RpcFramework.refer(HelloService.class, "127.0.0.1", 1234);  
        for (int i = 0; i < Integer.MAX_VALUE; i ++) {  
            String hello = service.hello("World" + i);  
            System.out.println(hello);  
            Thread.sleep(1000);  
        }  
    }  
}

本文分享自微信公众号 - Java架构沉思录(code-thinker)

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2019-12-20

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 没用过分布式锁?那你该好好看看这篇文章。

    原文:https://www.cnblogs.com/JJJ1990/p/10496850.html

    黄泽杰
  • 通俗易懂的Nginx工作原理

    作者:Rick617原文:https://www.jianshu.com/p/6215e5d24553

    黄泽杰
  • 那天晚上和@FeignClient注解的深度交流

    主要还是在技术群里看到有同学在问相关问题,比如: contextId 是干嘛的?name 相同的多个 Client 会报错?

    黄泽杰
  • 【RPC 专栏】简单了解RPC实现原理

    芋道源码
  • HDOJ/HDU 1804 Deli Deli(英语单词复数形式~)

    Problem Description Mrs. Deli is running the delicatessen store “Deli Deli”. L...

    谙忆
  • spring-boot-2.0.3不一样系列之番外篇 - springboot事件机制,绝对有值得你看的地方

           本来打算这篇继续和大家一起讨论springboot启动源码的,可觉得再讲源码估计大家都没有看下去的勇气了,那么今天,我们不讲springboot的...

    青石路
  • 设计模式--动态代理的思考

    在一些第三方框架中经常能看到动态代理的案例,尤其是RPC框架,ORM框架等,该篇将分析这些实现的原理,另外延伸在业务中的使用示例.

    屈定
  • uva----11729 Commando war (突击战争)

    G Commando War Input: Standard Input Output: Standard Output “Wa...

    Gxjun
  • 旷视高额融资后,商汤一口气发布11款产品,并新开两大业务线

    继旷视宣布获得7.5亿美元D轮融资后,商汤今日又一口气发布了11款新品,涉及了AI教育、AI医疗、自动驾驶、智慧零售、智慧城市、AR娱乐等多个应用领域。

    镁客网
  • Linux杂谈:Mac/Linux下配置远程Linux服务器免密登录

    你还在为你每次打开测试环境、生产环境需要登录而犯愁吗? 登录是必须的,但密码是可或缺的!!!

    恒宇少年

扫码关注云+社区

领取腾讯云代金券