RPC框架几行代码就够了
转于作者梁飞在公司的Blog:
http://pt.alibaba-inc.com/wp/experience_1330/simple-rpc-framework.html
因为要给百技上实训课,让新同学们自行实现一个简易RPC框架,在准备PPT时,就想写个示例,发现原来一个RPC框架只要一个类,10来分钟就可以写完了,虽然简陋,也晒晒:
- /*
- * 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();
- }
- }
- });
- }
- }
用起来也像模像样:
(1) 定义服务接口
- /*
- * 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) 实现服务
- /*
- * 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) 暴露服务
- /*
- * 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) 引用服务
- /*
- * 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);
- }
- }
- }
from: http://javatar.iteye.com/blog/1123915
RPC框架几行代码就够了相关推荐
- 读梁飞-RPC框架几行代码就够了 有感
梁飞-dubbo框架的设计者,是一位阿里的资深架构师 RPC框架几行代码就够了,这篇文章十分适合不是很了解RPC的人看一遍,最好是自己敲一遍.注释,对入参的处理,对流用后进行关闭,动态代理的使用. 这 ...
- 还发愁项目经验吗?基于Netty实现分布式RPC框架[附完整代码]
写给大家的话 最近我收到很多读者的来信,对如何学习分布式.如何进行项目实践和提高编程能力,存在很多疑问. 分布式那么难,怎么学?为什么看了那么多书还是掌握不了? 开源的框架比如Dubbo代码太多了,完 ...
- awvs 13使用_如何解密AWVS?15行代码就够了!
项目介绍 AWVS一直以来在圈子中都比较火,以速度快和高准确性深受大家喜爱.很多人想研究其运作机制却因闭源而不得其解. 今天这里通过一个极其简单的方式,只用几行代码就能让你一见其核心代码.这是最新解码 ...
- 5行代码秀碾压,比Keras还好用的fastai来了,尝鲜PyTorch 1.0必备伴侣
休假栗 问耕 假装发自 凹非寺 量子位 出品 | 公众号 QbitAI PyTorch 1.0来了~ 在今天的F8(Facebook开发者大会)上,深度学习框架PyTorch 1.0 rc1版如期发布 ...
- 100 行代码透彻解析 RPC 原理
欢迎关注方志朋的博客,回复"666"获面试宝典 文章来源:https://sourl.cn/HpZHvy 引 言 本文主要论述的是"RPC 实现原理",那么首先 ...
- 4行代码,让app自动化框架支持 webview 混合应用操作
移动端 app 自动化框架很多,但是有一些框架因为不支持混合应用测试,一直没有完全流行.比较典型的是经典的 Python 框架 uiautomator2, 这个框架简单好用,没有 appium 那样复 ...
- 都说Djnago框架重,那就让哥用15行代码写个django web程序!
很多初学django的小伙伴都会了解到,django是个大而全的网络框架,本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能.要学这么多内容,要学到猴年马月啊!? 不过世界真是奇妙, ...
- 蒋金楠:200行代码7个对象《ASP.NET Core框架揭密》苏州.NET俱乐部课程分享
[课程名称] <ASP.NET Core框架揭密> [老师介绍] 蒋金楠,同程艺龙机票事业部技术专家,微软最有价值专家(MVP,连续12),多本.NET专著作者.博客园Artech,公众号 ...
- JAVA5000行代码什么概念_GitHub - catstiger/mvc: 一个不超过5000行代码的,快速,简单,易用的MVC框架。...
一个不超过5000行代码的,快速,简单,易用的MVC框架. 我们的目的是: 让MVC回归其最初的目的. 因简单而快速,超过目前各种主流MVC. 零侵入,零配置,易于测试,并且让开发者感觉不到MVC的存 ...
最新文章
- scrum回顾_Scrum和SAFe之间有什么不同
- [学习笔记]矩阵乘法及其优化dp
- 机器学习中的数据不平衡问题----通过随机采样比例大的类别使得训练集中大类的个数与小类相当,或者模型中加入惩罚项...
- 工厂方法模式和简单工厂模式的区别
- Nauuo and Votes
- sql server 2008学习3 表组织和索引组织
- emacs的使用方法
- 外卖和快递行业数据_抢人大战愈演愈烈,东莞再现用工荒!不只流向外卖、快递等行业...
- php微信支付使用ajax,接入微信公众号支付,选择支付方式后,只弹出“error’”(php)...
- clocks_per_sec 时间不正确_你该拥有的不只是护肤品,还有正确护肤时间表
- golang,接口的demo01
- POJ-1426 Find The Multiple
- 线性代数知识点总结_[Github项目推荐] 机器学习amp; Python 知识点速查表
- Sharepoint学习笔记---Linq to Sharepoint--增,删,改操作
- HTML的发展史及背景,HTML发展史 - 蓝蓝设计每日一贴
- 域用户账户、组的管理
- AIOC4专业版快速修复CAD文件关联,双击dwg文件没反应
- 数论-快速幂、矩阵快速幂、慢速乘
- 小小白学习c语言分享
- Java练习题__删除公共字符
热门文章
- 云宇宙iwemeta: 亚马逊全面进军元宇宙
- 工具用的好下班走的早
- GMIS 2017 Martin Müller演讲:深度学习时代的启发式搜索
- 计算图上的微积分:Backpropagation 微积分 SOTON数据分析 · 2015-09-06 08:52 [译] 计算图上的微积分:Backpropagation 引言 Backprop
- 深度学习之四:常用模型和方法
- 不热衷黄金、地产的美国人喜欢投资什么?
- 高并发编程-Thread#interrupt用法及源码分析
- Quartz-SchedulerListener解读
- Spring4.X系列之AOP基础篇
- 计算机目录读取,从项目目录中读取SQL查询文件(Read SQL query file from project directory)...