转于作者梁飞在公司的Blog: 
http://pt.alibaba-inc.com/wp/experience_1330/simple-rpc-framework.html

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

Java代码  
  1. /*
  2. * Copyright 2011 Alibaba.com All right reserved. This software is the
  3. * confidential and proprietary information of Alibaba.com ("Confidential
  4. * Information"). You shall not disclose such Confidential Information and shall
  5. * use it only in accordance with the terms of the license agreement you entered
  6. * into with Alibaba.com.
  7. */
  8. package com.alibaba.study.rpc.framework;
  9. import java.io.ObjectInputStream;
  10. import java.io.ObjectOutputStream;
  11. import java.lang.reflect.InvocationHandler;
  12. import java.lang.reflect.Method;
  13. import java.lang.reflect.Proxy;
  14. import java.net.ServerSocket;
  15. import java.net.Socket;
  16. /**
  17. * RpcFramework
  18. *
  19. * @author william.liangf
  20. */
  21. public class RpcFramework {
  22. /**
  23. * 暴露服务
  24. *
  25. * @param service 服务实现
  26. * @param port 服务端口
  27. * @throws Exception
  28. */
  29. public static void export(final Object service, int port) throws Exception {
  30. if (service == null)
  31. throw new IllegalArgumentException("service instance == null");
  32. if (port <= 0 || port > 65535)
  33. throw new IllegalArgumentException("Invalid port " + port);
  34. System.out.println("Export service " + service.getClass().getName() + " on port " + port);
  35. ServerSocket server = new ServerSocket(port);
  36. for(;;) {
  37. try {
  38. final Socket socket = server.accept();
  39. new Thread(new Runnable() {
  40. @Override
  41. public void run() {
  42. try {
  43. try {
  44. ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
  45. try {
  46. String methodName = input.readUTF();
  47. Class<?>[] parameterTypes = (Class<?>[])input.readObject();
  48. Object[] arguments = (Object[])input.readObject();
  49. ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
  50. try {
  51. Method method = service.getClass().getMethod(methodName, parameterTypes);
  52. Object result = method.invoke(service, arguments);
  53. output.writeObject(result);
  54. } catch (Throwable t) {
  55. output.writeObject(t);
  56. } finally {
  57. output.close();
  58. }
  59. } finally {
  60. input.close();
  61. }
  62. } finally {
  63. socket.close();
  64. }
  65. } catch (Exception e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. }).start();
  70. } catch (Exception e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. }
  75. /**
  76. * 引用服务
  77. *
  78. * @param <T> 接口泛型
  79. * @param interfaceClass 接口类型
  80. * @param host 服务器主机名
  81. * @param port 服务器端口
  82. * @return 远程服务
  83. * @throws Exception
  84. */
  85. @SuppressWarnings("unchecked")
  86. public static <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {
  87. if (interfaceClass == null)
  88. throw new IllegalArgumentException("Interface class == null");
  89. if (! interfaceClass.isInterface())
  90. throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");
  91. if (host == null || host.length() == 0)
  92. throw new IllegalArgumentException("Host == null!");
  93. if (port <= 0 || port > 65535)
  94. throw new IllegalArgumentException("Invalid port " + port);
  95. System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":" + port);
  96. return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationHandler() {
  97. public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {
  98. Socket socket = new Socket(host, port);
  99. try {
  100. ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
  101. try {
  102. output.writeUTF(method.getName());
  103. output.writeObject(method.getParameterTypes());
  104. output.writeObject(arguments);
  105. ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
  106. try {
  107. Object result = input.readObject();
  108. if (result instanceof Throwable) {
  109. throw (Throwable) result;
  110. }
  111. return result;
  112. } finally {
  113. input.close();
  114. }
  115. } finally {
  116. output.close();
  117. }
  118. } finally {
  119. socket.close();
  120. }
  121. }
  122. });
  123. }
  124. }

用起来也像模像样:

(1) 定义服务接口

Java代码  
  1. /*
  2. * Copyright 2011 Alibaba.com All right reserved. This software is the
  3. * confidential and proprietary information of Alibaba.com ("Confidential
  4. * Information"). You shall not disclose such Confidential Information and shall
  5. * use it only in accordance with the terms of the license agreement you entered
  6. * into with Alibaba.com.
  7. */
  8. package com.alibaba.study.rpc.test;
  9. /**
  10. * HelloService
  11. *
  12. * @author william.liangf
  13. */
  14. public interface HelloService {
  15. String hello(String name);
  16. }

(2) 实现服务

Java代码  
  1. /*
  2. * Copyright 2011 Alibaba.com All right reserved. This software is the
  3. * confidential and proprietary information of Alibaba.com ("Confidential
  4. * Information"). You shall not disclose such Confidential Information and shall
  5. * use it only in accordance with the terms of the license agreement you entered
  6. * into with Alibaba.com.
  7. */
  8. package com.alibaba.study.rpc.test;
  9. /**
  10. * HelloServiceImpl
  11. *
  12. * @author william.liangf
  13. */
  14. public class HelloServiceImpl implements HelloService {
  15. public String hello(String name) {
  16. return "Hello " + name;
  17. }
  18. }

(3) 暴露服务

Java代码  
  1. /*
  2. * Copyright 2011 Alibaba.com All right reserved. This software is the
  3. * confidential and proprietary information of Alibaba.com ("Confidential
  4. * Information"). You shall not disclose such Confidential Information and shall
  5. * use it only in accordance with the terms of the license agreement you entered
  6. * into with Alibaba.com.
  7. */
  8. package com.alibaba.study.rpc.test;
  9. import com.alibaba.study.rpc.framework.RpcFramework;
  10. /**
  11. * RpcProvider
  12. *
  13. * @author william.liangf
  14. */
  15. public class RpcProvider {
  16. public static void main(String[] args) throws Exception {
  17. HelloService service = new HelloServiceImpl();
  18. RpcFramework.export(service, 1234);
  19. }
  20. }

(4) 引用服务

Java代码  
  1. /*
  2. * Copyright 2011 Alibaba.com All right reserved. This software is the
  3. * confidential and proprietary information of Alibaba.com ("Confidential
  4. * Information"). You shall not disclose such Confidential Information and shall
  5. * use it only in accordance with the terms of the license agreement you entered
  6. * into with Alibaba.com.
  7. */
  8. package com.alibaba.study.rpc.test;
  9. import com.alibaba.study.rpc.framework.RpcFramework;
  10. /**
  11. * RpcConsumer
  12. *
  13. * @author william.liangf
  14. */
  15. public class RpcConsumer {
  16. public static void main(String[] args) throws Exception {
  17. HelloService service = RpcFramework.refer(HelloService.class, "127.0.0.1", 1234);
  18. for (int i = 0; i < Integer.MAX_VALUE; i ++) {
  19. String hello = service.hello("World" + i);
  20. System.out.println(hello);
  21. Thread.sleep(1000);
  22. }
  23. }
  24. }

from: http://javatar.iteye.com/blog/1123915

RPC框架几行代码就够了相关推荐

  1. 读梁飞-RPC框架几行代码就够了 有感

    梁飞-dubbo框架的设计者,是一位阿里的资深架构师 RPC框架几行代码就够了,这篇文章十分适合不是很了解RPC的人看一遍,最好是自己敲一遍.注释,对入参的处理,对流用后进行关闭,动态代理的使用. 这 ...

  2. 还发愁项目经验吗?基于Netty实现分布式RPC框架[附完整代码]

    写给大家的话 最近我收到很多读者的来信,对如何学习分布式.如何进行项目实践和提高编程能力,存在很多疑问. 分布式那么难,怎么学?为什么看了那么多书还是掌握不了? 开源的框架比如Dubbo代码太多了,完 ...

  3. awvs 13使用_如何解密AWVS?15行代码就够了!

    项目介绍 AWVS一直以来在圈子中都比较火,以速度快和高准确性深受大家喜爱.很多人想研究其运作机制却因闭源而不得其解. 今天这里通过一个极其简单的方式,只用几行代码就能让你一见其核心代码.这是最新解码 ...

  4. 5行代码秀碾压,比Keras还好用的fastai来了,尝鲜PyTorch 1.0必备伴侣

    休假栗 问耕 假装发自 凹非寺 量子位 出品 | 公众号 QbitAI PyTorch 1.0来了~ 在今天的F8(Facebook开发者大会)上,深度学习框架PyTorch 1.0 rc1版如期发布 ...

  5. 100 行代码透彻解析 RPC 原理

    欢迎关注方志朋的博客,回复"666"获面试宝典 文章来源:https://sourl.cn/HpZHvy 引 言 本文主要论述的是"RPC 实现原理",那么首先 ...

  6. 4行代码,让app自动化框架支持 webview 混合应用操作

    移动端 app 自动化框架很多,但是有一些框架因为不支持混合应用测试,一直没有完全流行.比较典型的是经典的 Python 框架 uiautomator2, 这个框架简单好用,没有 appium 那样复 ...

  7. 都说Djnago框架重,那就让哥用15行代码写个django web程序!

    很多初学django的小伙伴都会了解到,django是个大而全的网络框架,本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能.要学这么多内容,要学到猴年马月啊!? 不过世界真是奇妙, ...

  8. 蒋金楠:200行代码7个对象《ASP.NET Core框架揭密》苏州.NET俱乐部课程分享

    [课程名称] <ASP.NET Core框架揭密> [老师介绍] 蒋金楠,同程艺龙机票事业部技术专家,微软最有价值专家(MVP,连续12),多本.NET专著作者.博客园Artech,公众号 ...

  9. JAVA5000行代码什么概念_GitHub - catstiger/mvc: 一个不超过5000行代码的,快速,简单,易用的MVC框架。...

    一个不超过5000行代码的,快速,简单,易用的MVC框架. 我们的目的是: 让MVC回归其最初的目的. 因简单而快速,超过目前各种主流MVC. 零侵入,零配置,易于测试,并且让开发者感觉不到MVC的存 ...

最新文章

  1. scrum回顾_Scrum和SAFe之间有什么不同
  2. [学习笔记]矩阵乘法及其优化dp
  3. 机器学习中的数据不平衡问题----通过随机采样比例大的类别使得训练集中大类的个数与小类相当,或者模型中加入惩罚项...
  4. 工厂方法模式和简单工厂模式的区别
  5. Nauuo and Votes
  6. sql server 2008学习3 表组织和索引组织
  7. emacs的使用方法
  8. 外卖和快递行业数据_抢人大战愈演愈烈,东莞再现用工荒!不只流向外卖、快递等行业...
  9. php微信支付使用ajax,接入微信公众号支付,选择支付方式后,只弹出“error’”(php)...
  10. clocks_per_sec 时间不正确_你该拥有的不只是护肤品,还有正确护肤时间表
  11. golang,接口的demo01
  12. POJ-1426 Find The Multiple
  13. 线性代数知识点总结_[Github项目推荐] 机器学习amp; Python 知识点速查表
  14. Sharepoint学习笔记---Linq to Sharepoint--增,删,改操作
  15. HTML的发展史及背景,HTML发展史 - 蓝蓝设计每日一贴
  16. 域用户账户、组的管理
  17. AIOC4专业版快速修复CAD文件关联,双击dwg文件没反应
  18. 数论-快速幂、矩阵快速幂、慢速乘
  19. 小小白学习c语言分享
  20. Java练习题__删除公共字符

热门文章

  1. 云宇宙iwemeta: 亚马逊全面进军元宇宙
  2. 工具用的好下班走的早
  3. GMIS 2017 Martin Müller演讲:深度学习时代的启发式搜索
  4. 计算图上的微积分:Backpropagation 微积分 SOTON数据分析 · 2015-09-06 08:52 [译] 计算图上的微积分:Backpropagation 引言 Backprop
  5. 深度学习之四:常用模型和方法
  6. 不热衷黄金、地产的美国人喜欢投资什么?
  7. 高并发编程-Thread#interrupt用法及源码分析
  8. Quartz-SchedulerListener解读
  9. Spring4.X系列之AOP基础篇
  10. 计算机目录读取,从项目目录中读取SQL查询文件(Read SQL query file from project directory)...