`

一个简单的RPC框架(转)

 
阅读更多

来自链接

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框架

    本篇将详细讲解如何使用socket、反射和序列化等技术来实现一个简单的RPC框架。 首先,让我们了解RPC的基本原理。在RPC模型中,客户端(Client)发起一个函数调用请求,这个请求包含了目标函数的名称和参数。RPC框架...

    自己写了一个RPC框架

    在这个场景中,你提到的是你自己编写了一个RPC框架,这是一项技术挑战,因为RPC框架涉及到网络通信、序列化、服务注册与发现等多个关键领域。 在你提供的博客链接中...

    如何实现一个简单的RPC框架

    实现一个简单的RPC框架主要涉及以下几个关键点: 1. **网络通信库**:Netty是一个高性能、异步事件驱动的网络应用框架,常用于构建高并发、低延迟的服务器。在RPC框架中,Netty可以处理客户端与服务端之间的网络...

    JAVA实现简单RPC框架

    在这个“JAVA实现简单RPC框架”的项目中,我们将探讨如何利用Java的核心特性来构建这样的框架。以下是关键知识点的详细说明: 1. **JDK动态代理**: JDK动态代理是Java提供的一种机制,可以在运行时创建一个实现了...

    jsonrpc是一个基于Java的高性能开源RPC框架

    在Java世界中,JSON-RPC作为一个高性能的开源RPC框架,为分布式系统中的服务调用提供了便利。这个框架允许应用程序通过网络在不同的进程之间传递方法调用,仿佛这些方法是在本地对象上调用一样。 JSON-RPC的核心...

    Java rpc框架简易版,类似dubbo分布式实现 (纯socket实现).zip

    本项目提供了一个简易版的Java RPC框架实现,旨在模仿著名的Dubbo框架,但采用了更基础的Socket通信方式进行分布式服务的搭建。以下是这个项目的核心知识点: 1. **RPC原理**:RPC使得客户端可以像调用本地方法一样...

    如何用Netty写一个自己的RPC框架

    3. RPC框架的工作机制:RPC框架允许一个应用调用另一个地址空间(通常是远程)中的方法。它主要依赖于网络通信、数据序列化和反序列化、动态代理、服务注册与发现等机制。 4. Java NIO(New I/O):NIO是Java提供的...

    RPC 框架学习 好的参考学习

    QiuRPC是基于Java实现的一个轻量级RPC框架,其设计目标是简单易用,易于理解和扩展。下面将从几个关键组件来分析QiuRPC的实现原理: 1. **服务接口与实现**: - QiuRPC允许开发者定义服务接口,然后在服务提供者侧...

    netty解读及如何设计一个简单的RPC框架

    一个简单的RPC框架通常包含以下几个核心组件: 1. **服务接口和服务实现**:定义了客户端可以调用的方法,服务实现则提供了这些方法的具体实现。 2. **服务注册与发现**:服务提供者将服务接口和实现注册到服务...

    myRpc一个极简单的RPC框架

    在这个名为“myRpc”的项目中,我们看到作者提供了一个非常基础的RPC实现,它可能是为了帮助学习者理解RPC的基本原理和工作流程,以及对比更成熟的框架如Hessian。 首先,我们要了解RPC的基本概念。RPC框架的核心...

    casock c++ RPC 框架

    在这个特定的案例中,我们关注的是一个名为"casock"的C++ RPC框架,它利用了google protobuf和boost asio库。以下是关于这个框架的详细知识点: 1. **casock框架**:casock是一个轻量级的RPC框架,旨在简化C++应用...

    最简单的JAVA RPC框架实现

    在Java中实现一个简单的RPC框架,我们需要理解以下几个关键概念和技术: 1. **网络通信**:RPC的核心是通过网络进行通信。在Java中,我们可以使用Socket API来实现客户端和服务器端之间的数据传输。Socket提供了低...

    java 手写rpc框架 rpc-server and rpc-client

    总的来说,Java手写RPC框架涉及了网络编程、序列化、多线程、服务治理等多个领域的知识,是一个很好的学习和实践分布式系统设计的平台。通过这个项目,开发者不仅可以提升技术水平,还能对分布式系统的运行机制有更...

    手写RPC框架1

    RPC(Remote Procedure Call)框架是实现分布式系统的关键技术,它允许一个程序调用另一个位于不同网络节点上的程序,使得远程服务调用就像本地调用一样简单。本文将探讨手写RPC框架的一些核心概念和组件。 首先,...

    python实现一个简单RPC框架的示例

    在Python中实现一个简单的RPC框架,我们可以利用Python的socket库来处理网络通信,以及JSON作为数据交换格式,因为JSON易于解析且广泛支持。 在RPC框架中,有以下几个关键组件: 1. **客户端(Client)**:发起RPC...

    Go实现简易RPC框架的方法步骤

    在Go语言中实现一个简单的RPC框架,主要涉及以下几个关键点: 1. **服务端设计**: - **函数映射**:服务端需要维护一个映射表,将接收到的函数名映射到实际的函数执行体。这通常通过`map[string]reflect.Value`...

    rest-rpc 简单易用的rpc框架 C++11

    `rest_rpc`是一个基于C++11开发的轻量级RPC(Remote Procedure Call)框架,它将RESTful API的设计理念与RPC技术相结合,为开发者提供了一种简单且高效的远程调用解决方案。本文将深入探讨`rest_rpc`的核心特性、...

    为什么说要搞定微服务架构,先搞定RPC框架

    以一个简单的本地函数调用为例: ```c++ int result = Add(1, 2); ``` 这里,我们调用了本地代码段中的`Add`函数,并传递了两个参数1和2。传入数据、传出数据以及代码段都在同一个进程空间内,这是本地函数调用的...

    Zookeeper实现简单的分布式RPC框架

    本文将深入探讨如何利用Zookeeper实现一个简单的分布式RPC(Remote Procedure Call)框架,同时也会涉及一些基础的源码分析和实用工具的使用。 首先,我们要理解Zookeeper的角色。Zookeeper是由Apache开发的一个...

    使用netty自定义rpc通信框架

    在IT行业中,RPC(Remote Procedure Call)是一种进程间通信机制,允许程序调用另一个进程中定义的函数或方法,就像调用本地函数一样简单。Netty是Java领域的一个高性能、异步事件驱动的网络应用程序框架,它极大地...

Global site tag (gtag.js) - Google Analytics