扒一扒RPC

简介: 扒一扒RPC

前言:

本篇文章是继JDK动态代理超详细源码分析之后的,因为RPC是基于动态代理的,想必大家都听过RPC,但是可能并没有针对的去了解过,因此本文打算以如下结构讲一讲RPC:


①尽量浅显易懂的描述RPC的工作原理

②分析一个RPC的Demo。


一、走近RPC


1.1 什么是RPC


RPC是远程程序调用的缩写,即远程过程调用,意思是可以在一台机器上调用远程的服务。在非分布式环境下,我们的程序调用服务都是本地调用,但是随着分布式结构的普遍,越来越多的应用需要解耦,将不同的独立功能部署发布成不同的服务供客户端调用.RPC就是为了解决这个问题的。


1.2 RPC原理


首先,我们心里带着这样的问题:要怎么样去调用远程的服务呢?

①肯定要知道IP和端口吧(确定唯一一个进程)

②肯定要知道调用什么服务吧(方法名和参数)

③调用服务后可能需要结果吧。

这三点又怎么实现呢,往下看?


RPC的设计由Client,Client stub,Network,Server stub,Server构成。

其中Client就是用来调用服务的,Cient stub是用来把调用的方法和参数序列化的(因为要在网络中传输,必须要把对象转变成字节),网络用来传输这些信息到服务器存根,服务器存根用来把这些信息反序列化的,服务器就是服务的提供者,最终调用的就是服务器提供的方法。


RPC的结构如下图:


image.png


图中1-10序号的含义如下:


  1. 客户端像调用本地服务似的调用远程服务;
  2. 客户端stub接收到调用后,将方法,参数序列化
  3. 客户端通过插座将消息发送到服务端
  4. Server stub收到消息后进行解码(将消息对象反序列化)
  5. 服务器存根根据解码结果调用本地的服务
  6. 本地服务执行(对于服务端来说是本地执行)并将结果返回给服务器存根
  7. 服务器存根将返回结果打包成消息(将结果消息对象序列化)
  8. 服务端通过插座将消息发送到客户端
  9. 客户端stub接收到结果消息,并进行解码(将结果消息发序列化)
  10. 客户端得到最终结果。


二、简单的RPC程序


在了解了RPC的大致原理之后,我们给出RPC的示例这里直接引用梁飞大神的代码,后面给出代码分析:

2.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.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();
               }
           }
       });
   }
}


2.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;
/**
* HelloService
*
* @author william.liangf
*/
public interface HelloService {
   String hello(String name);
}

2.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;
/**
* HelloServiceImpl
*
* @author william.liangf
*/
public class HelloServiceImpl implements HelloService {
   public String hello(String name) {
       return "Hello " + name;
   }
}


2.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;
/**
* RpcProvider
*
* @author william.liangf
*/
public class RpcProvider {
   public static void main(String[] args) throws Exception {
       HelloService service = new HelloServiceImpl();
       RpcFramework.export(service, 1234);
   }
}


2.5 引用服务


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


代码写的简单清晰又很能说明问题,不得不佩服大佬的技术。回过头来,我们分析一下这个程序的结构。


再次把RPC的5个组成部分回顾一下:Cient,Client-stub,Network,服务器,服务器存根。


首先2.2定义服务接口状语从句:2.3服务实现都是在服务器端实现的。写完了服务之后需要发布出去,以供客户端调用于是,在2.4服务暴露中调用export方法把服务发布出去。 export有一个参数是服务实现的对象服务,这就给客户端提供了调用的可能性。我们看看导出里都做了什么:


ServerSocket server = new ServerSocket(port);

创建ServerSocket并绑定接口。然后是个无限循环,因为一直提供服务嘛


final Socket socket = server.accept();

以阻塞的方式监听网络连接。开一个线程去处理客户端发过来的信息(反序列化方法名,参数类型,参数对象),这部分功能相当于服务器存根。然后通过反射机制调用服务对象的方法,并把得到的结果序列化返回给客户端。


看客户端,也就是2.5引用服务。通过参考函数得到服务的对象(这个对象就是通过动态代理生成的代理对象)然后像调用本地方法一样调用远程方法我们看下参阅里都做了什么。


return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[] {interfaceClass}, new InvocationHandler()
{...重写invoke方法})


主要是返回服务实现类的代理对象,我们在分析JDK动态代理的时候知道,当我们调用代理对象的方法时,调用方法会被执行。


在调用方法中,


Socket socket = new Socket(host, port);


创建的Socket与服务器取得连接,然后将方法名,方法类型,方法参数序列化发给服务器端,这部分功能相当于客户存根。然后获得服务器端发送过来的结果。

这样RPC的功能就实现了。

目录
相关文章
|
JavaScript 前端开发 Java
11 个最佳的 Python 编译器和解释器
11 个最佳的 Python 编译器和解释器
874 1
|
项目管理
项目管理办公室(Project Management Office)
当今的商业环境变得越来越复杂,项目管理成为了成功实施战略和取得竞争优势的关键。为了更好地管理和协调项目,许多组织都建立了项目管理办公室(PMO)。本文将详细探讨PMO的概念、功能以及它们在项目管理中的重要性。
|
API 数据安全/隐私保护
Argo CD接入LDAP认证或者gitea认证的方法
argocd默认是通过修改argocd-cm来添加账户的,添加完账户后,还需要使用argocd客户端命令去给账户设置密码,这肯定是比较麻烦的,为了方便使用,我们可以接入ldap认证或者gitea的oauth2认证。 这里我们主要写ldap认证,因为gitea没有提供组信息给dex,而ldap能返回组信息 ,gitea的接入会在文章的末尾进行简单介绍 关键词:argocd ldap dex
2382 1
Argo CD接入LDAP认证或者gitea认证的方法
|
消息中间件 存储 RocketMQ
Rocketmq如何保证消息不丢失
文章分析了RocketMQ如何通过生产者端的同步发送与重试机制、Broker端的持久化存储与消息重试投递策略、以及消费者端的手动提交ack与幂等性处理,来确保消息在整个传输和消费过程中的不丢失。
|
Cloud Native jenkins 持续交付
【云原生】使用PyCharm上传代码到Gitlab仓库并在Jenkins构建
【云原生】使用PyCharm上传代码到Gitlab仓库并在Jenkins构建
786 0
|
JavaScript 前端开发 开发者
介绍如何在WebStorm中调试JavaScript文件
介绍如何在WebStorm中调试JavaScript文件
539 1
|
并行计算 索引 Python
讨论如何优化 DataFrame 操作,减少内存占用和提高执行速度
【5月更文挑战第19天】优化 DataFrame 操作涉及选择合适的数据类型、避免复制、使用向量化、高效迭代和设置索引。通过这些策略,如使用 `np.int8` 节省内存,直接修改列数据,利用 `itertuples`,设置分类数据类型,以及分块和并行计算,可以显著减少内存占用和提高执行速度,从而更好地处理大规模数据。实践中需结合具体情况综合运用,不断测试和优化。
580 2
|
消息中间件 NoSQL 关系型数据库
实战:如何防止mq消费方消息重复消费、rocketmq理论概述、rocketmq组成、普通消息的发送
实战:如何防止mq消费方消息重复消费 如果因为网络延迟等原因,mq无法及时接收到消费方的应答,导致mq重试。(计算机网络)。在重试过程中造成重复消费的问题
3126 1
实战:如何防止mq消费方消息重复消费、rocketmq理论概述、rocketmq组成、普通消息的发送
|
前端开发 API
【strapi系列】strapi在postman中如何调试public和认证用户Authorization的接口
【strapi系列】strapi在postman中如何调试public和认证用户Authorization的接口
258 1
|
消息中间件 存储 负载均衡
什么是RabbitMQ?
RabbitMQ是一个开源的消息代理软件,用于在分布式系统中传递消息。它实现了高级消息队列协议(AMQP),提供了一种可靠的、强大的、灵活的消息传递机制,使得不同应用程序或组件之间可以轻松地进行通信。
526 0