`
无量
  • 浏览: 1133978 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Rpc转

 
阅读更多
转于自己在公司的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.   
  10. import java.io.ObjectInputStream;  
  11. import java.io.ObjectOutputStream;  
  12. import java.lang.reflect.InvocationHandler;  
  13. import java.lang.reflect.Method;  
  14. import java.lang.reflect.Proxy;  
  15. import java.net.ServerSocket;  
  16. import java.net.Socket;  
  17.   
  18. /** 
  19.  * RpcFramework 
  20.  *  
  21.  * @author william.liangf 
  22.  */  
  23. public class RpcFramework {  
  24.   
  25.     /** 
  26.      * 暴露服务 
  27.      *  
  28.      * @param service 服务实现 
  29.      * @param port 服务端口 
  30.      * @throws Exception 
  31.      */  
  32.     public static void export(final Object service, int port) throws Exception {  
  33.         if (service == null)  
  34.             throw new IllegalArgumentException("service instance == null");  
  35.         if (port <= 0 || port > 65535)  
  36.             throw new IllegalArgumentException("Invalid port " + port);  
  37.         System.out.println("Export service " + service.getClass().getName() + " on port " + port);  
  38.         ServerSocket server = new ServerSocket(port);  
  39.         for(;;) {  
  40.             try {  
  41.                 final Socket socket = server.accept();  
  42.                 new Thread(new Runnable() {  
  43.                     @Override  
  44.                     public void run() {  
  45.                         try {  
  46.                             try {  
  47.                                 ObjectInputStream input = new ObjectInputStream(socket.getInputStream());  
  48.                                 try {  
  49.                                     String methodName = input.readUTF();  
  50.                                     Class<?>[] parameterTypes = (Class<?>[])input.readObject();  
  51.                                     Object[] arguments = (Object[])input.readObject();  
  52.                                     ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());  
  53.                                     try {  
  54.                                         Method method = service.getClass().getMethod(methodName, parameterTypes);  
  55.                                         Object result = method.invoke(service, arguments);  
  56.                                         output.writeObject(result);  
  57.                                     } catch (Throwable t) {  
  58.                                         output.writeObject(t);  
  59.                                     } finally {  
  60.                                         output.close();  
  61.                                     }  
  62.                                 } finally {  
  63.                                     input.close();  
  64.                                 }  
  65.                             } finally {  
  66.                                 socket.close();  
  67.                             }  
  68.                         } catch (Exception e) {  
  69.                             e.printStackTrace();  
  70.                         }  
  71.                     }  
  72.                 }).start();  
  73.             } catch (Exception e) {  
  74.                 e.printStackTrace();  
  75.             }  
  76.         }  
  77.     }  
  78.   
  79.     /** 
  80.      * 引用服务 
  81.      *  
  82.      * @param <T> 接口泛型 
  83.      * @param interfaceClass 接口类型 
  84.      * @param host 服务器主机名 
  85.      * @param port 服务器端口 
  86.      * @return 远程服务 
  87.      * @throws Exception 
  88.      */  
  89.     @SuppressWarnings("unchecked")  
  90.     public static <T> T refer(final Class<T> interfaceClass, final String host, final int port) throws Exception {  
  91.         if (interfaceClass == null)  
  92.             throw new IllegalArgumentException("Interface class == null");  
  93.         if (! interfaceClass.isInterface())  
  94.             throw new IllegalArgumentException("The " + interfaceClass.getName() + " must be interface class!");  
  95.         if (host == null || host.length() == 0)  
  96.             throw new IllegalArgumentException("Host == null!");  
  97.         if (port <= 0 || port > 65535)  
  98.             throw new IllegalArgumentException("Invalid port " + port);  
  99.         System.out.println("Get remote service " + interfaceClass.getName() + " from server " + host + ":" + port);  
  100.         return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationHandler() {  
  101.             public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable {  
  102.                 Socket socket = new Socket(host, port);  
  103.                 try {  
  104.                     ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());  
  105.                     try {  
  106.                         output.writeUTF(method.getName());  
  107.                         output.writeObject(method.getParameterTypes());  
  108.                         output.writeObject(arguments);  
  109.                         ObjectInputStream input = new ObjectInputStream(socket.getInputStream());  
  110.                         try {  
  111.                             Object result = input.readObject();  
  112.                             if (result instanceof Throwable) {  
  113.                                 throw (Throwable) result;  
  114.                             }  
  115.                             return result;  
  116.                         } finally {  
  117.                             input.close();  
  118.                         }  
  119.                     } finally {  
  120.                         output.close();  
  121.                     }  
  122.                 } finally {  
  123.                     socket.close();  
  124.                 }  
  125.             }  
  126.         });  
  127.     }  
  128.   
  129. }  


用起来也像模像样: 

(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. /** 
  11.  * HelloService 
  12.  *  
  13.  * @author william.liangf 
  14.  */  
  15. public interface HelloService {  
  16.   
  17.     String hello(String name);  
  18.   
  19. }  


(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. /** 
  11.  * HelloServiceImpl 
  12.  *  
  13.  * @author william.liangf 
  14.  */  
  15. public class HelloServiceImpl implements HelloService {  
  16.   
  17.     public String hello(String name) {  
  18.         return "Hello " + name;  
  19.     }  
  20.   
  21. }  


(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.   
  10. import com.alibaba.study.rpc.framework.RpcFramework;  
  11.   
  12. /** 
  13.  * RpcProvider 
  14.  *  
  15.  * @author william.liangf 
  16.  */  
  17. public class RpcProvider {  
  18.   
  19.     public static void main(String[] args) throws Exception {  
  20.         HelloService service = new HelloServiceImpl();  
  21.         RpcFramework.export(service, 1234);  
  22.     }  
  23.   
  24. }  


(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.   
  10. import com.alibaba.study.rpc.framework.RpcFramework;  
  11.   
  12. /** 
  13.  * RpcConsumer 
  14.  *  
  15.  * @author william.liangf 
  16.  */  
  17. public class RpcConsumer {  
  18.       
  19.     public static void main(String[] args) throws Exception {  
  20.         HelloService service = RpcFramework.refer(HelloService.class"127.0.0.1"1234);  
  21.         for (int i = 0; i < Integer.MAX_VALUE; i ++) {  
  22.             String hello = service.hello("World" + i);  
  23.             System.out.println(hello);  
  24.             Thread.sleep(1000);  
  25.         }  
  26.     }  
  27.       
  28. }  
分享到:
评论

相关推荐

    用RPC机制把本地调用转换成远程调用

    用RPC机制把本地调用转换成远程调用,参考的是SUN的官方文档。

    拍拍贷微服务rpc框架源码.zip

    拍拍贷微服务rpc框架源码.zip # 拍拍贷微服务体系 拍拍贷微服务体系是拍拍贷基础框架部总结内部微服务多年实践,参考、吸收大量业内解决方案形成的适合中型互联网公司的微服务解决方案。 拍拍贷微服务体系主要组成...

    RPC8211FS RGMII/SGMII 1000M Ethernet PHY

    RPC8211FS是一种高度集成的以太网收发器,符合10Base-T、100Base-TX 和1000Base-T IEEE 802.3标准。它提供了通过 CAT.5 UTP 电缆传输和接收以太网数据包所需的所有物理层功能。 RPC8211FS为基于 IEEE 1588和802.1 AS...

    java_rpc_demo

    (1)用java写的RPC调用的demo。通过这个demo,可以了解RPC的基本原理。 (2)没有用到其他的jar包,java对象和流之间的转换用的是java.io.ObjectInputStream和java.io.ObjectOutputStream。 (3)下载解压,可以...

    go-plugin:RPC上的Golang插件系统

    通过RPC转到插件系统 go-plugin是基于RPC的Go(golang)插件系统。 这是HashiCorp工具使用超过4年的插件系统。 当最初为创建时,它又被 , 和。 虽然插件系统是通过RPC进行的,但目前仅设计为在本地[可靠]网络上...

    超轻量压缩传输js2java rpc框架(XtZPStream v1.0)

    1、JS2Java RPC:能够在javascript的web浏览器环境中指定java类,获取该类实例的属性, 调用该实例的方法 2、支持复杂js对象作为入参:能够传递复杂的JavaScript Object对象作为调用参数, 在java中得到对应的Map...

    修改phprpc源码以支持集合类的string类型的转换

    NULL 博文链接:https://chembo.iteye.com/blog/905038

    jsonrpc4j:Java的JSON-RPC

    Java的JSON-RPC 该项目旨在提供轻松实现Java编程语言的JSON-RPC的功能。 jsonrpc4j使用库在json对象(以及与JSON-RPC相关的其他东西)之间来回转换java对象。 功能包括: 流服务器( InputStream \ OutputStream ...

    ocaml-rpc:轻型库可处理OCaml中的RPC

    OCaml-RPC-远程过程调用(RPC)库 ocaml-rpc是一个库,提供使用XML或JSON作为传输编码的远程过程调用(RPC)。 传输机制本身不在此库的范围内,因为所有转换都是从字符串到字符串的。 odoc生成的文档可在。 RPC类型 ...

    eth2cfx-relay:中继器,以将以太坊JSON-RPC调用转换为Conflux JSON-RPC调用。 (仅适用于未签名的通话互动)

    Conflux节点使用与以太坊JSON-RPC稍有不同的函数调用 使用JSON-RPC服务器作为中继 中继将呼叫转换为ETH呼叫转换为CFX呼叫(预处理) 中继将CFX响应转换为ETH响应(后处理) 指令 yarn start :启动继电器 yarn ...

    json-rpc-1.0.zip

    Java转换JSON的包

    python如何通过protobuf实现rpc

    由于项目组现在用的rpc是基于google protobuf rpc协议实现的,所以花了点时间了解下protobuf rpc。rpc对于做分布式系统的人来说肯定不陌生,对于rpc不了解的童鞋可以自行google,这里只是...代理封装调用信息并将调用转

    CSDN-0019-20221118-GF3一级转二级软件(RPC系数).rar

    使用RPC系数,对高分三号一级产品进行几何校正

    115:115助手将下载链接导出到aria2-rpc

    如果您将aria2 1.15.2(或更高版本)与'JSON-RPC PATH'一起使用,例如设置--rpc-user=&lt;username&gt; --rpc-passwd= 使用http://localhost:6800/jsonrpc#max-connection-per-server=5&split=10设置特定文件的下载选项...

    rpc:Discord RPC使您的Discord配置文件看起来更漂亮

    rpc Discord RPC使您的Discord配置文件看起来更漂亮。 指示 首先进入VSC(Visual ...转到cmd和cd进入rpc的目录。 然后输入以下内容:节点main.js,现在将其保留在那里。 当您关闭它时,RPC将消失,就像我的父亲一样

    xml-rpc.js:跨域 JavaScript 的 XML-RPC 库

    xml-rpc.js 跨域 JavaScript 的 XML-RPC 库。 基于 Carlos Eduardo Goncalves 最初编写的 Mimic JS 库; 许可证见下文。 为 XML-RPC 提供易于使用的面向对象的接口。 将对象透明地转换为 JS 文字是实用的(例如 ...

    simple-json-rpc:Java的简单JSON-RPC

    简单的JSON-RPC 一个用于将协议简单集成到Java应用程序的库。 目的是提供一种简单,快速和可靠的方法,以将JSON-RPC 2.0协议集成到服务器和/或客户端上的Java应用程序中。 为此,您需要配置JsonRpcClient或...

    simple-thrift-tutorial:此代码将使您在5分钟内使用Apache Thrift进行设置

    简单的节俭教程创建一个定义服务的.thrift文件thrift --gen java ... 处理器是IDL编译器生成的服务器端存根,它将网络RPC转换为对处理程序的调用。 MultiplicationClient.java-构造了客户端对象并将其提供给

    ts-to-open-rpc:用于将TypeScript接口转换为OpenRPC接口描述的命令行实用程序

    ts-open-rpc 用于将TypeScript接口转换为OpenRPC接口描述的命令行实用程序。 注意:早期MVP。 许多待办事项。 用法 首先,拉回购和yarn link或npm link 。 程序输出到标准输出: ts-to-open-rpc METHOD_NAME ...

    Discord-Custom-RPC:带有GUI的Discord自定义RPC应用程序

    只需转到“选项卡并下载最新版本。 从源头运行 确保已安装Python 3。 如果您使用的是Linux,请运行python pip install -r requirements.txt或python3 -m pip install --requirement requirements.txt 。 然后,...

Global site tag (gtag.js) - Google Analytics