核心框架类

/*
* 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();
               }
           }
       });
   }
}

定义服务接口

/*
* 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);
}

实现服务

/*
* 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;
   }
}

暴露服务

/*
* 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);
   }
}

引用服务

/*
* 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);
       }
   }
}

总结

这个简单的例子的实现思路是使用阻塞的socket IO流来进行server和client的通信,也就是rpc应用中服务提供方和服务消费方。并且是端对端的,用端口号来直接进行通信。方法的远程调用使用的是jdk的动态代理,参数的序列化也是使用的最简单的objectStream。

真实的rpc框架会对上面的实现方式进行替换,采用更快更稳定,更高可用易扩展,更适宜分布式场景的中间件,技术来替换。例如使用netty的nio特性达到非阻塞的通信,使用zookeeper统一管理服务注册与发现,解决了端对端不灵活的劣势。代理方式有cglib字节码技术。序列化方式有hession2,fastjson等等。使用原生的jdk api就展现给各位读者一个生动形象的rpc demo,实在是强。rpc框架解决的不仅仅是技术层面的实现,还考虑到了rpc调用中的诸多问题,重试机制,超时配置…这些就需要去了解成熟的rpc框架是如果考虑这些问题的了。

推荐一个轻量级的rpc框架:motan。weibo团队在github开源的一个rpc框架,有相应的文档,用起来感觉比dubbo要轻量级,易上手。

简单了解RPC实现原理-copy的更多相关文章

  1. RPC实现原理(HSF、dubbo) 从头开始(一)

    前言 阔别了很久博客园,虽然看了以前写的很多东西感觉好幼稚,但是还是觉得应该把一些自己觉得有用的东西和大家分享.废话不多说,现在开始进入正题. 之前的六年工作经验,呆过了一些大公司,每个在大公司呆过的 ...

  2. 分布式架构的基石.简单的 RPC 框架实现(JAVA)

    前言 RPC 的全称是 Remote Procedure Call,它是一种进程间通信方式.允许像调用本地服务一样调用远程服务. 学习来源:<分布式系统架构:原理与实践> - 李林锋 1. ...

  3. Java实现简单的RPC框架(美团面试)

    一.RPC简介 RPC,全称为Remote Procedure Call,即远程过程调用,它是一个计算机通信协议.它允许像调用本地服务一样调用远程服务.它可以有不同的实现方式.如RMI(远程方法调用) ...

  4. 如何实现一个简单的RPC

    在如何给老婆解释什么是RPC中,我们讨论了RPC的实现思路. 那么这一次,就让我们通过代码来实现一个简单的RPC吧! RPC的实现原理 正如上一讲所说,RPC主要是为了解决的两个问题: 解决分布式系统 ...

  5. 动手实现一个简单的 rpc 框架到入门 grpc (上)

    rpc 全称 Remote Procedure Call 远程过程调用,即调用远程方法.我们调用当前进程中的方法时很简单,但是想要调用不同进程,甚至不同主机.不同语言中的方法时就需要借助 rpc 来实 ...

  6. 徒手撸一个简单的RPC框架

    来源:https://juejin.im/post/5c4481a4f265da613438aec3 之前在牛逼哄哄的 RPC 框架,底层到底什么原理得知了RPC(远程过程调用)简单来说就是调用远程的 ...

  7. RPC通信原理概述

    RPC通信原理概述 1.RPC概述 1.什么是RPC RPC(Remote Procedure Call Protocol)远程过程调用协议.它是一种通过网络从远程计算机程序上请求服务,而不需要了解底 ...

  8. 聊聊RPC及其原理

    什么是RPC? RPC是Remote Procedure Call的缩写,想Client-Servier一样的远程过程调用,也就是调用远程服务就跟调用本地服务一样方便,一般用于将程序部署在不同的机器上 ...

  9. 自己用 Netty 实现一个简单的 RPC

    目录: 需求 设计 实现 创建 maven 项目,导入 Netty 4.1.16. 项目目录结构 设计接口 提供者相关实现 消费者相关实现 测试结果 总结 源码地址:github 地址 前言 众所周知 ...

  10. 最简单的RPC框架实现

    通过java原生的序列化,Socket通信,动态代理和反射机制,实现一个简单的RPC框架,由三部分组成: 1.服务提供者,运行再服务端,负责提供服务接口定义和服务实现类 2.服务发布者,运行再RPC服 ...

随机推荐

  1. 使用 vscode 编译+运行 typescropt Mac win同理

    一..d.ts文件最好在src/typings 目录下,可在tsconfig.json 文件配置 二.vs 监听文件变化,自动编译ts文件 tsconfig.json { "compiler ...

  2. 如何使用ConsulManager来优雅的管理主机监控与站点监控

    概述 ConsulManager是一个使用Flask+Vue开发的Consul WEB管理工具,比官方自带的WEB UI实现了更多的功能. 可以方便的对Consul Services进行增删改查,支持 ...

  3. Xor-FWT 的另一种理解方式

    Xor-FWT 的另一种理解方式 学习 \(\text{Fennec's Algorithm}\) 的额外收获,顺手记录一下. 假设我们要求两个长度为 \(n\) 的数组的异或卷积,为方便起见令 \( ...

  4. C++中的各种锁

    在多线程开发中,经常会遇到数据同步,很多情况下用锁都是一个很好的选择.C++中常用的锁主要有下面几种: 互斥锁(std::mutex) 这是最基本的一种锁.它用于保护共享资源,在任意时刻,最多只有一个 ...

  5. rce临时文件上传[RCE1]P8

    rce临时文件上传[RCE1]P8 /[A-Za-z0-9!~^|&]+/i 匹配了我能想到的所有绕过方法,想到临时文件上传,是否可以执行/tmp/?????????这个文件呢 /tmp/?? ...

  6. highcharts中的折线图

    折现图表的样式如下所示: 整体的一个设置代码如下: that.options = { title: { text: null }, subtitle: { text: null }, yAxis: { ...

  7. npm之基本使用

    # 查看镜像源 npm config get registry # 设置镜像源 # 腾讯云 npm config set registry http://mirrors.cloud.tencent.c ...

  8. 如何在原生鸿蒙中进行RN的断点调试

    方式一  chrome devtools的方式 第一步:metro的方式加载bundle 先设置好原生这边的代码,然后记得打开RN服务器. 注意这个enableDebugger的值一定要设置为true ...

  9. LALR语法分析表

    LALR语法分析表 1.LALR(向前看-LR)技术 2.在实践中常用,分析表比规范LR分析表小 LALR(1)项集族的内核的高效计算方法 1.构造G的LR(0)项集族的内核 2.确定自发生的符号 3 ...

  10. 【二分+前缀和+后缀和】codeforces 2026 D. Sums of Segments

    题目 https://codeforces.com/problemset/problem/2026/D 题意 第一行输入一个正整数 \(n(1 \leq n \leq 3e5)\),第二行输入 \(n ...