神烦,老大要我写一个RPC框架!

开发 架构 开发工具
如果大家对 RPC 有一些了解的话,或多或者都会听到过一些大名鼎鼎的 RPC 框架,比如 Dubbo、gRPC。但是大部分人对于他们底层的实现原理其实不甚了解。

 如果大家对 RPC 有一些了解的话,或多或者都会听到过一些大名鼎鼎的 RPC 框架,比如 Dubbo、gRPC。但是大部分人对于他们底层的实现原理其实不甚了解。

[[341322]]

图片来自 Pexels

有一种比较好的学习方式就是:如果你想要了解一个框架的原理,你可以尝试去写一个简易版的框架出来,就比如如果你想理解 Spring IOC 的思想,最好的方式就是自己实现一个小型的 IOC 容器,自己慢慢体会。

所以本文尝试带领大家去设计一个小型的 RPC 框架,同时对于框架会保持一些拓展点。

通过阅读本文,你可以收获:

  • 理解 RPC 框架最核心的理念。
  • 学习在设计框架的时候,如何保持拓展性。

本文会依赖一些组件,他们是实现 RPC 框架必要的一些知识,文中会尽量降低这些知识带来的障碍。

但是,最好期望读者有以下知识基础:

  • Zookeeper 基本入门
  • Netty 基本入门

RPC 框架应该长什么样子

我们首先来看一下:一个 RPC 框架是什么东西?我们最直观的感觉就是:

集成了 RPC 框架之后,通过配置一个注册中心的地址。一个应用(称为服务提供者)将某个接口(interface)“暴露”出去,另外一个应用(称为服务消费者)通过“引用”这个接口(interface),然后调用了一下,就很神奇的可以调用到另外一个应用的方法了

给我们的感觉就好像调用了一个本地方法一样。即便两个应用不是在同一个 JVM 中甚至两个应用都不在同一台机器中。

那他们是如何做到的呢?当我们的服务消费者调用某个 RPC 接口的方法之后,它的底层会通过动态代理,然后经过网络调用,去到服务提供者的机器上,然后执行对应的方法。

接着方法的结果通过网络传输返回到服务消费者那里,然后就可以拿到结果了。

整个过程如下图:

那么这个时候,可能有人会问了:服务消费者怎么知道服务提供者在哪台机器的哪个端口呢?

这个时候,就需要“注册中心”登场了,具体来说是这样子的:

  • 服务提供者在启动的时候,将自己应用所在机器的信息提交到注册中心上面。
  • 服务消费者在启动的时候,将需要消费的接口所在机器的信息抓回来。

这样一来,服务消费者就有了一份服务提供者所在的机器列表了。

 

“服务消费者”拿到了“服务提供者”的机器列表就可以通过网络请求来发起请求了。

网络客户端,我们应该采用什么呢?有几种选择:

  • 使用 JDK 原生 BIO(也就是 ServerSocket 那一套)。阻塞式 IO 方法,无法支撑高并发。
  • 使用 JDK 原生 NIO(Selector、SelectionKey 那一套)。非阻塞式 IO,可以支持高并发,但是自己实现复杂,需要处理各种网络问题。
  • 使用大名鼎鼎的 NIO 框架 Netty,天然支持高并发,封装好,API 易用。

“服务消费者”拿到了“服务提供者”的机器列表就可以通过网络请求来发起请求了。

作为一个有追求的程序员,我们要求开发出来的框架要求支持高并发、又要求简单、还要快。

当然是选择 Netty 来实现了,使用 Netty 的一些很基本的 API 就能满足我们的需求。

网络协议定义

当然了,既然我们要使用网络传输数据。我们首先要定义一套网络协议出来。

你可能又要问了,啥叫网络协议?网络协议,通俗理解,意思就是说我们的客户端发送的数据应该长什么样子,服务端可以去解析出来知道要做什么事情。

话不多说,上代码,假设我们现在服务提供者有两个类:

 

  1. // com.study.rpc.test.producer.HelloService 
  2. public interface HelloService { 
  3.  
  4.     String sayHello(TestBean testBean); 
  5.  
  6. // com.study.rpc.test.producer.TestBean 
  7. public class TestBean { 
  8.  
  9.     private String name
  10.     private Integer age; 
  11.  
  12.     public TestBean(String nameInteger age) { 
  13.         this.name = name
  14.         this.age = age; 
  15.     } 
  16.     // getter setter 

现在我要调用 HelloService.sayHello(TestBean testBean) 这个方法。

作为“服务消费者”,应该怎么定义我们的请求,从而让服务端知道我是要调用这个方法呢?

这需要我们将这个接口信息产生一个唯一的标识:这个标识会记录了接口名、具体是那个方法、然后具体参数是什么!

然后将这些信息组织起来发送给服务端,我这里的方式是将信息保存为一个 JSON 格式的字符串来传输。

比如上面的接口我们传输的数据大概是这样的:

 

  1.     "interfaces": "interface=com.study.rpc.test.producer.HelloService&method=sayHello& 
  2.     parameter=com.study.rpc.test.producer.TestBean", 
  3.     "requestId""3"
  4.     "parameter": { 
  5.         "com.study.rpc.test.producer.TestBean": { 
  6.             "age": 20, 
  7.             "name""张三" 
  8.         } 
  9.     } 

嗯,我这里用一个 JSON 来标识这次调用是调用哪个接口的哪个方法,其中 interface 标识了唯一的类,parameter 标识了里面具体有哪些参数, 其中 key 就是参数的类全限定名,value 就是这个类的 JSON 信息。

可能看到这里,大家可能有意见了:数据不一定用 JSON 格式传输啊,而且使用 JSON 也不一定性能最高啊。

你使用 JDK 的 Serializable 配合 Netty 的 ObjectDecoder 来实现,这当然也可以,其实这里是一个拓展点,我们应该要提供多种序列化方式来供用户选择。

但是这里选择了 JSON 的原因是因为它比较直观,对于写文章来说比较合理。

开发服务提供者

嗯,搞定了网络协议之后,我们开始开发“服务提供者”了。对于服务提供者,因为我们这里是写一个简单版本的 RPC 框架,为了保持简洁。

我们不会引入类似 Spring 之类的容器框架,所以我们需要定义一个服务提供者的配置类,它用于定义这个服务提供者是什么接口,然后它具体的实例对象是什么:

  1. public class ServiceConfig{ 
  2.  
  3.     public Class type; 
  4.  
  5.     public T instance; 
  6.  
  7.     public ServiceConfig(Classtype, T instance) { 
  8.         this.type = type; 
  9.         this.instance = instance; 
  10.     } 
  11.  
  12.     public ClassgetType() { 
  13.         return type; 
  14.     } 
  15.  
  16.     public void setType(Classtype) { 
  17.         this.type = type; 
  18.     } 
  19.  
  20.     public T getInstance() { 
  21.         return instance; 
  22.     } 
  23.  
  24.     public void setInstance(T instance) { 
  25.         this.instance = instance; 
  26.     } 

有了这个东西之后,我们就知道需要暴露哪些接口了。为了框架有一个统一的入口,我定义了一个类叫做 ApplicationContext,可以认为这是一个应用程序上下文,他的构造函数,接收 2 个参数。

代码如下:

  1. public ApplicationContext(String registryUrl, ListserviceConfigs){ 
  2.     // 1. 保存需要暴露的接口配置 
  3.     this.serviceConfigs = serviceConfigs == null ? new ArrayList<>() : serviceConfigs; 
  4.  
  5.     // step 2: 实例化注册中心 
  6.     initRegistry(registryUrl); 
  7.  
  8.     // step 3: 将接口注册到注册中心,从注册中心获取接口,初始化服务接口列表 
  9.     RegistryInfo registryInfo = null
  10.     InetAddress addr = InetAddress.getLocalHost(); 
  11.     String hostname = addr.getHostName(); 
  12.     String hostAddress = addr.getHostAddress(); 
  13.     registryInfo = new RegistryInfo(hostname, hostAddress, port); 
  14.     doRegistry(registryInfo); 
  15.  
  16.  
  17.     // step 4:初始化Netty服务器,接受到请求,直接打到服务提供者的service方法中 
  18.     if (!this.serviceConfigs.isEmpty()) { 
  19.         // 需要暴露接口才暴露 
  20.         nettyServer = new NettyServer(this.serviceConfigs, interfaceMethods); 
  21.         nettyServer.init(port); 
  22.     } 

注册中心设计

这里分为几个步骤,首先保存了接口配置,接着初始化注册中心,因为注册中心可能会提供多种来供用户选择,所以这里需要定义一个注册中心的接口:

  1. public interface Registry { 
  2.     /** 
  3.      * 将生产者接口注册到注册中心 
  4.      * 
  5.      * @param clazz        类 
  6.      * @param registryInfo 本机的注册信息 
  7.      */ 
  8.     void register(Class clazz, RegistryInfo registryInfo) throws Exception; 

这里我们提供一个注册的方法,这个方法的语义是将 clazz 对应的接口注册到注册中心。

接收两个参数,一个是接口的 class 对象,另一个是注册信息,里面包含了本机的一些基本信息,如下:

  1. public class RegistryInfo { 
  2.  
  3.     private String hostname; 
  4.     private String ip; 
  5.     private Integer port; 
  6.  
  7.     public RegistryInfo(String hostname, String ip, Integer port) { 
  8.         this.hostname = hostname; 
  9.         this.ip = ip; 
  10.         this.port = port; 
  11.     } 
  12.     // getter setter 

好了,定义好注册中心,回到之前的实例化注册中心的地方,代码如下:

  1. /** 
  2.  * 注册中心 
  3.  */ 
  4. private Registry registry; 
  5.  
  6. private void initRegistry(String registryUrl) { 
  7.     if (registryUrl.startsWith("zookeeper://")) { 
  8.         registryUrl = registryUrl.substring(12); 
  9.         registry = new ZookeeperRegistry(registryUrl); 
  10.     } else if (registryUrl.startsWith("multicast://")) { 
  11.         registry = new MulticastRegistry(registryUrl); 
  12.     } 

这里逻辑也非常简单,就是根据 url 的 schema 来判断是那个注册中心,注册中心这里实现了 2 个实现类,分别使用 Zookeeper 作为注册中心,另外一个是使用广播的方式作为注册中心。

广播注册中心这里仅仅是做个示范,内部没有实现。我们主要是实现了 Zookeeper 的注册中心。

当然了,如果有兴趣,可以实现更多的注册中心供用户选择,比如 Redis 之类的,这里只是为了保持“拓展点”。

那么实例化完注册中心之后,回到上面的代码。

注册服务提供者

  1. // step 3: 将接口注册到注册中心,从注册中心获取接口,初始化服务接口列表 
  2. RegistryInfo registryInfo = null
  3. InetAddress addr = InetAddress.getLocalHost(); 
  4. String hostname = addr.getHostName(); 
  5. String hostAddress = addr.getHostAddress(); 
  6. registryInfo = new RegistryInfo(hostname, hostAddress, port); 
  7. doRegistry(registryInfo); 

这里逻辑很简单,就是获取本机的的基本信息构造成 RegistryInfo,然后调用了 doRegistry 方法:

  1. /** 
  2.  * 接口方法对应method对象 
  3.  */ 
  4. private MapinterfaceMethods = new ConcurrentHashMap<>(); 
  5.  
  6. private void doRegistry(RegistryInfo registryInfo) throws Exception { 
  7.     for (ServiceConfig config : serviceConfigs) { 
  8.         Class type = config.getType(); 
  9.         registry.register(type, registryInfo); 
  10.         Method[] declaredMethods = type.getDeclaredMethods(); 
  11.         for (Method method : declaredMethods) { 
  12.             String identify = InvokeUtils.buildInterfaceMethodIdentify(type, method); 
  13.             interfaceMethods.put(identify, method); 
  14.         } 
  15.     } 

这里做了两件事情:

  • 将接口注册到注册中心中。
  • 对于每一个接口的每一个方法,生成一个唯一标识,保存在 interfaceMethods 集合中。

下面分别分析这两件事情,首先是注册方法:因为我们用到了 Zookeeper,为了方便,引入了 Zookeeper 的客户端框架 Curator。

  1. <dependency> 
  2.     <groupId>org.apache.curatorgroupId> 
  3.     <artifactId>curator-recipesartifactId> 
  4.     <version>2.3.0version> 
  5. dependency> 

接着看代码:

  1. public class ZookeeperRegistry implements Registry { 
  2.  
  3.     private CuratorFramework client; 
  4.  
  5.     public ZookeeperRegistry(String connectString) { 
  6.         RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); 
  7.         client = CuratorFrameworkFactory.newClient(connectString, retryPolicy); 
  8.         client.start(); 
  9.         try { 
  10.             Stat myRPC = client.checkExists().forPath("/myRPC"); 
  11.             if (myRPC == null) { 
  12.                 client.create() 
  13.                         .creatingParentsIfNeeded() 
  14.                         .forPath("/myRPC"); 
  15.             } 
  16.             System.out.println("Zookeeper Client初始化完毕......"); 
  17.         } catch (Exception e) { 
  18.             e.printStackTrace(); 
  19.         } 
  20.     } 
  21.  
  22.  
  23.     @Override 
  24.     public void register(Class clazz, RegistryInfo registryInfo) throws Exception { 
  25.         // 1. 注册的时候,先从zk中获取数据 
  26.         // 2. 将自己的服务器地址加入注册中心中 
  27.  
  28.         // 为每一个接口的每一个方法注册一个临时节点,然后key为接口方法的唯一标识,data为服务地址列表 
  29.  
  30.         Method[] declaredMethods = clazz.getDeclaredMethods(); 
  31.         for (Method method : declaredMethods) { 
  32.             String key = InvokeUtils.buildInterfaceMethodIdentify(clazz, method); 
  33.             String path = "/myRPC/" + key
  34.             Stat stat = client.checkExists().forPath(path); 
  35.             ListregistryInfos; 
  36.             if (stat != null) { 
  37.                 // 如果这个接口已经有人注册过了,把数据拿回来,然后将自己的信息保存进去 
  38.                 byte[] bytes = client.getData().forPath(path); 
  39.                 String data = new String(bytes, StandardCharsets.UTF_8); 
  40.                 registryInfos = JSONArray.parseArray(data, RegistryInfo.class); 
  41.                 if (registryInfos.contains(registryInfo)) { 
  42.                     // 正常来说,zk的临时节点,断开连接后,直接就没了,但是重启会经常发现存在节点,所以有了这样的代码 
  43.                     System.out.println("地址列表已经包含本机【" + key + "】,不注册了"); 
  44.                 } else { 
  45.                     registryInfos.add(registryInfo); 
  46.                     client.setData().forPath(path, JSONArray.toJSONString(registryInfos).getBytes()); 
  47.                     System.out.println("注册到注册中心,路径为:【" + path + "】 信息为:" + registryInfo); 
  48.                 } 
  49.             } else { 
  50.                 registryInfos = new ArrayList<>(); 
  51.                 registryInfos.add(registryInfo); 
  52.                 client.create() 
  53.                         .creatingParentsIfNeeded() 
  54.                         // 临时节点,断开连接就关闭 
  55.                         .withMode(CreateMode.EPHEMERAL) 
  56.                         .forPath(path, JSONArray.toJSONString(registryInfos).getBytes()); 
  57.                 System.out.println("注册到注册中心,路径为:【" + path + "】 信息为:" + registryInfo); 
  58.             } 
  59.         } 
  60.     } 

Zookeeper 注册中心在初始化的时候,会建立好连接。然后注册的时候,针对 clazz 接口的每一个方法,都会生成一个唯一标识。

这里使用了InvokeUtils.buildInterfaceMethodIdentify方法:

  1. public static String buildInterfaceMethodIdentify(Class clazz, Method method) { 
  2.     Map<String, String> map = new LinkedHashMap<>(); 
  3.     map.put("interface", clazz.getName()); 
  4.     map.put("method", method.getName()); 
  5.     Parameter[] parameters = method.getParameters(); 
  6.     if (parameters.length > 0) { 
  7.         StringBuilder param = new StringBuilder(); 
  8.         for (int i = 0; i < parameters.length; i++) { 
  9.             Parameter p = parameters[i]; 
  10.             param.append(p.getType().getName()); 
  11.             if (i < parameters.length - 1) { 
  12.                 param.append(","); 
  13.             } 
  14.         } 
  15.         map.put("parameter", param.toString()); 
  16.     } 
  17.     return map2String(map); 
  18.  
  19. public static String map2String(Map<String, String> map) { 
  20.     StringBuilder sb = new StringBuilder(); 
  21.     Iterator<map.entry<string, <="" span="">String>> iterator = map.entrySet().iterator(); 
  22.     while (iterator.hasNext()) { 
  23.         Map.Entry<String, String> entry = iterator.next(); 
  24.         sb.append(entry.getKey() + "=" + entry.getValue()); 
  25.         if (iterator.hasNext()) { 
  26.             sb.append("&"); 
  27.         } 
  28.     } 
  29.     return sb.toString(); 

其实就是对接口的方法使用他们的限定名和参数来组成一个唯一的标识,比如 HelloService#sayHello(TestBean) 生成的大概是这样的:

  1. interface=com.study.rpc.test.producer.HelloService&method=sayHello& 
  2. parameter=com.study.rpc.test.producer.TestBean 

接下来的逻辑就简单了,在 Zookeeper 中的 /myRPC 路径下面建立临时节点,节点名称为我们上面的接口方法唯一标识,数据内容为机器信息。

之所以采用临时节点是因为:如果机器宕机了,连接断开之后,消费者可以通过 Zookeeper 的 watcher 机制感知到。

大概看起来是这样的:

  1. /myRPC/interface=com.study.rpc.test.producer.HelloService&method=sayHello& 
  2.    parameter=com.study.rpc.test.producer.TestBean 
  3.    [ 
  4.        { 
  5.            "hostname":peer1, 
  6.            "port":8080 
  7.        }, 
  8.        { 
  9.            "hostname":peer2, 
  10.            "port":8081 
  11.        } 
  12.    ] 

通过这样的方式,在服务消费的时候就可以拿到这样的注册信息,然后知道可以调用那台机器的那个端口。

好了,注册中心弄完了之后,我们回到前面说的注册方法做的第二件事情,我们将每一个接口方法标识的方法放入了一个 map 中:

  1. /** 
  2.  * 接口方法对应method对象 
  3.  */ 
  4. private Map<String, Method> interfaceMethods = new ConcurrentHashMap<>(); 

这个的原因是因为,我们在收到网络请求的时候,需要调用反射的方式调用 Method 对象,所以存起来。

启动网络服务端接受请求

接下来我们就可以看第四步了:

 

  1. // step 4:初始化Netty服务器,接受到请求,直接打到服务提供者的service方法中 
  2. if (!this.serviceConfigs.isEmpty()) { 
  3.     // 需要暴露接口才暴露 
  4.     nettyServer = new NettyServer(this.serviceConfigs, interfaceMethods); 
  5.     nettyServer.init(port); 

因为这里使用 Netty 来做的所以需要引入 Netty 的依赖:

  1. <dependency> 
  2.     <groupId>io.nettygroupId> 
  3.     <artifactId>netty-allartifactId> 
  4.     <version>4.1.30.Finalversion> 
  5. dependency> 

接着来分析:

 

  1. public class NettyServer { 
  2.  
  3.     /** 
  4.      * 负责调用方法的handler 
  5.      */ 
  6.     private RpcInvokeHandler rpcInvokeHandler; 
  7.  
  8.     public NettyServer(ListserverConfigs, MapinterfaceMethods)throws InterruptedException { 
  9.         this.rpcInvokeHandler = new RpcInvokeHandler(serverConfigs, interfaceMethods); 
  10.     } 
  11.  
  12.     public int init(int port) throws Exception { 
  13.         EventLoopGroup bossGroup = new NioEventLoopGroup(); 
  14.         EventLoopGroup workerGroup = new NioEventLoopGroup(); 
  15.         ServerBootstrap b = new ServerBootstrap(); 
  16.         b.group(bossGroup, workerGroup) 
  17.                 .channel(NioServerSocketChannel.class) 
  18.                 .option(ChannelOption.SO_BACKLOG, 1024) 
  19.                 .childHandler(new ChannelInitializer(){ 
  20.                     @Override 
  21.                     protected void initChannel(SocketChannel ch) throws Exception { 
  22.                         ByteBuf delimiter = Unpooled.copiedBuffer("$$"); 
  23.                         // 设置按照分隔符“&&”来切分消息,单条消息限制为 1MB 
  24.                         ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024 * 1024, delimiter)); 
  25.                         ch.pipeline().addLast(new StringDecoder()); 
  26.                         ch.pipeline().addLast().addLast(rpcInvokeHandler); 
  27.                     } 
  28.                 }); 
  29.         ChannelFuture sync = b.bind(port).sync(); 
  30.         System.out.println("启动NettyService,端口为:" + port); 
  31.         return port; 
  32.     } 

这部分主要的都是 Netty 的 API,我们不做过多的说明,就简单的说一下:

  • 我们通过“&&”作为标识符号来区分两条信息,然后一条信息的最大长度为 1MB。
  • 所有逻辑都在 RpcInvokeHandler 中,这里面传进去了配置的服务接口实例,以及服务接口实例每个接口方法唯一标识对应的 Method 对象的 Map 集合。

 

  1. public class RpcInvokeHandler extends ChannelInboundHandlerAdapter { 
  2.  
  3.     /** 
  4.      * 接口方法唯一标识对应的Method对象 
  5.      */ 
  6.     private Map<String, Method> interfaceMethods; 
  7.     /** 
  8.      * 接口对应的实现类 
  9.      */ 
  10.     private Map<class, Object> interfaceToInstance; 
  11.  
  12.     /** 
  13.      * 线程池,随意写的,不要吐槽 
  14.      */ 
  15.     private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 
  16.             50, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100), 
  17.             new ThreadFactory() { 
  18.                 AtomicInteger m = new AtomicInteger(0); 
  19.  
  20.                 @Override 
  21.                 public Thread newThread(Runnable r) { 
  22.                     return new Thread(r, "IO-thread-" + m.incrementAndGet()); 
  23.                 } 
  24.             }); 
  25.  
  26.  
  27.     public RpcInvokeHandler(ListserviceConfigList, 
  28.                             Map<String, Method> interfaceMethods) { 
  29.         this.interfaceToInstance = new ConcurrentHashMap<>(); 
  30.         this.interfaceMethods = interfaceMethods; 
  31.         for (ServiceConfig config : serviceConfigList) { 
  32.             interfaceToInstance.put(config.getType(), config.getInstance()); 
  33.         } 
  34.     } 
  35.  
  36.     @Override 
  37.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 
  38.         try { 
  39.             String message = (String) msg; 
  40.             // 这里拿到的是一串JSON数据,解析为Request对象, 
  41.             // 事实上这里解析网络数据,可以用序列化方式,定一个接口,可以实现JSON格式序列化,或者其他序列化 
  42.             // 但是demo版本就算了。 
  43.             System.out.println("接收到消息:" + msg); 
  44.             RpcRequest request = RpcRequest.parse(message, ctx); 
  45.             threadPoolExecutor.execute(new RpcInvokeTask(request)); 
  46.         } finally { 
  47.             ReferenceCountUtil.release(msg); 
  48.         } 
  49.     } 
  50.  
  51.     @Override 
  52.     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 
  53.         ctx.flush(); 
  54.     } 
  55.  
  56.     @Override 
  57.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 
  58.         System.out.println("发生了异常..." + cause); 
  59.         cause.printStackTrace(); 
  60.         ctx.close(); 
  61.     } 
  62.  
  63.     public class RpcInvokeTask implements Runnable { 
  64.  
  65.         private RpcRequest rpcRequest; 
  66.  
  67.         RpcInvokeTask(RpcRequest rpcRequest) { 
  68.             this.rpcRequest = rpcRequest; 
  69.         } 
  70.  
  71.         @Override 
  72.         public void run() { 
  73.             try { 
  74.                 /* 
  75.                  * 数据大概是这样子的 
  76.                  * {"interfaces":"interface=com.study.rpc.test.producer.HelloService&method=sayHello¶meter=com 
  77.                  * .study.rpc.test.producer.TestBean","requestId":"3","parameter":{"com.study.rpc.test.producer 
  78.                  * .TestBean":{"age":20,"name":"张三"}}} 
  79.                  */ 
  80.                 // 这里希望能拿到每一个服务对象的每一个接口的特定声明 
  81.                 String interfaceIdentity = rpcRequest.getInterfaceIdentity(); 
  82.                 Method method = interfaceMethods.get(interfaceIdentity); 
  83.                 Map<String, String> map = string2Map(interfaceIdentity); 
  84.                 String interfaceName = map.get("interface"); 
  85.                 Class interfaceClass = Class.forName(interfaceName); 
  86.                 Object o = interfaceToInstance.get(interfaceClass); 
  87.                 String parameterString = map.get("parameter"); 
  88.                 Object result; 
  89.                 if (parameterString != null) { 
  90.                     String[] parameterTypeClass = parameterString.split(","); 
  91.                     Map<String, Object> parameterMap = rpcRequest.getParameterMap(); 
  92.                     Object[] parameterInstance = new Object[parameterTypeClass.length]; 
  93.                     for (int i = 0; i < parameterTypeClass.length; i++) { 
  94.                         String parameterClazz = parameterTypeClass[i]; 
  95.                         parameterInstance[i] = parameterMap.get(parameterClazz); 
  96.                     } 
  97.                     result = method.invoke(o, parameterInstance); 
  98.                 } else { 
  99.                     result = method.invoke(o); 
  100.                 } 
  101.                 // 写回响应 
  102.                 ChannelHandlerContext ctx = rpcRequest.getCtx(); 
  103.                 String requestId = rpcRequest.getRequestId(); 
  104.                 RpcResponse response = RpcResponse.create(JSONObject.toJSONString(result), interfaceIdentity, 
  105.                         requestId); 
  106.                 String s = JSONObject.toJSONString(response) + "$$"
  107.                 ByteBuf byteBuf = Unpooled.copiedBuffer(s.getBytes()); 
  108.                 ctx.writeAndFlush(byteBuf); 
  109.                 System.out.println("响应给客户端:" + s); 
  110.             } catch (Exception e) { 
  111.                 e.printStackTrace(); 
  112.             } 
  113.         } 
  114.  
  115.          public static Map<String, String> string2Map(String str) { 
  116.             String[] split = str.split("&"); 
  117.             Map<String, String> map = new HashMap<>(16); 
  118.             for (String s : split) { 
  119.                 String[] split1 = s.split("="); 
  120.                 map.put(split1[0], split1[1]); 
  121.             } 
  122.             return map; 
  123.          } 
  124.     } 

这里说明一下上面的逻辑:channelRead 方法用于接收消息,接收到的就是我们前面分析的那个 JSON 格式的数据,接着我们将消息解析成 RpcRequest。

  1. public class RpcRequest { 
  2.  
  3.     private String interfaceIdentity; 
  4.  
  5.     private Map<String, Object> parameterMap = new HashMap<>(); 
  6.  
  7.     private ChannelHandlerContext ctx; 
  8.  
  9.     private String requestId; 
  10.  
  11.     public static RpcRequest parse(String message, ChannelHandlerContext ctx) throws ClassNotFoundException { 
  12.         /* 
  13.          * { 
  14.          *   "interfaces":"interface=com.study.rpc.test.producer.HelloService&method=sayHello2¶meter=java.lang 
  15.          * .String,com.study.rpc.test.producer.TestBean", 
  16.          *   "parameter":{ 
  17.          *      "java.lang.String":"haha"
  18.          *      "com.study.rpc.test.producer.TestBean":{ 
  19.          *              "name":"小王"
  20.          *              "age":20 
  21.          *        } 
  22.          *    } 
  23.          * } 
  24.          */ 
  25.         JSONObject jsonObject = JSONObject.parseObject(message); 
  26.         String interfaces = jsonObject.getString("interfaces"); 
  27.  
  28.         JSONObject parameter = jsonObject.getJSONObject("parameter"); 
  29.         Set<String> strings = parameter.keySet(); 
  30.         RpcRequest request = new RpcRequest(); 
  31.         request.setInterfaceIdentity(interfaces); 
  32.         Map<String, Object> parameterMap = new HashMap<>(16); 
  33.  
  34.         String requestId = jsonObject.getString("requestId"); 
  35.  
  36.         for (String key : strings) { 
  37.             if (key.equals("java.lang.String")) { 
  38.                 parameterMap.put(key, parameter.getString(key)); 
  39.             } else { 
  40.                 Class clazz = Class.forName(key); 
  41.                 Object object = parameter.getObject(key, clazz); 
  42.                 parameterMap.put(key, object); 
  43.             } 
  44.         } 
  45.         request.setParameterMap(parameterMap); 
  46.         request.setCtx(ctx); 
  47.         request.setRequestId(requestId); 
  48.         return request; 
  49.     } 

接着从 request 中解析出来需要调用的接口,然后通过反射调用对应的接口,得到结果后我们将响应封装成 PrcResponse 写回给客户端:

  1. public class RpcResponse { 
  2.  
  3.     private String result; 
  4.  
  5.     private String interfaceMethodIdentify; 
  6.  
  7.     private String requestId; 
  8.  
  9.     public String getResult() { 
  10.         return result; 
  11.     } 
  12.  
  13.     public void setResult(String result) { 
  14.         this.result = result; 
  15.     } 
  16.  
  17.     public static RpcResponse create(String result, String interfaceMethodIdentify, String requestId) { 
  18.         RpcResponse response = new RpcResponse(); 
  19.         response.setResult(result); 
  20.         response.setInterfaceMethodIdentify(interfaceMethodIdentify); 
  21.         response.setRequestId(requestId); 
  22.         return response; 
  23.     } 

里面包含了请求的结果 JSON 串,接口方法唯一标识,请求 ID。数据大概看起来这个样子:

  1. {"interfaceMethodIdentify":"interface=com.study.rpc.test.producer.HelloService&method=sayHello& 
  2. parameter=com.study.rpc.test.producer.TestBean","requestId":"3", 
  3. "result":"\"牛逼,我收到了消息:TestBean{name='张三', age=20}\""

通过这样的信息,客户端就可以通过响应结果解析出来。

测试服务提供者

既然我们代码写完了,现在需要测试一把,首先我们先写一个 HelloService 的实现类出来:

  1. public class HelloServiceImpl implements HelloService { 
  2.  
  3.     @Override 
  4.     public String sayHello(TestBean testBean) { 
  5.         return "牛逼,我收到了消息:" + testBean; 
  6.     } 

接着编写服务提供者代码:

  1. public class TestProducer { 
  2.  
  3.     public static void main(String[] args) throws Exception { 
  4.         String connectionString = "zookeeper://localhost1:2181,localhost2:2181,localhost3:2181"
  5.         HelloService service = new HelloServiceImpl(); 
  6.         ServiceConfig config = new ServiceConfig<>(HelloService.class, service); 
  7.         ListserviceConfigList = new ArrayList<>(); 
  8.         serviceConfigList.add(config); 
  9.         ApplicationContext ctx = new ApplicationContext(connectionString, serviceConfigList, 
  10.         null, 50071); 
  11.     } 

接着启动起来,看到日志:

  1. Zookeeper Client初始化完毕...... 
  2. 注册到注册中心,路径为:【/myRPC/interface=com.study.rpc.test.producer.HelloService& 
  3. method=sayHello¶meter=com.study.rpc.test.producer.TestBean】 
  4. 信息为:RegistryInfo{hostname='localhost', ip='192.168.16.7', port=50071} 
  5. 启动NettyService,端口为:50071 

这个时候,我们期望用 NettyClient 发送请求:

  1.     "interfaces": "interface=com.study.rpc.test.producer.HelloService& 
  2.     method=sayHello¶meter=com.study.rpc.test.producer.TestBean", 
  3.     "requestId""3"
  4.     "parameter": { 
  5.         "com.study.rpc.test.producer.TestBean": { 
  6.             "age": 20, 
  7.             "name""张三" 
  8.         } 
  9.     } 

得到的响应应该是:

  1. {"interfaceMethodIdentify":"interface=com.study.rpc.test.producer.HelloService&method=sayHello& 
  2. parameter=com.study.rpc.test.producer.TestBean","requestId":"3", 
  3. "result":"\"牛逼,我收到了消息:TestBean{name='张三', age=20}\""

那么,可以编写一个测试程序(这个程序仅仅用于中间测试用,读者不必理解):

  1. public class NettyClient { 
  2.     public static void main(String[] args) { 
  3.         EventLoopGroup group = new NioEventLoopGroup(); 
  4.         try { 
  5.             Bootstrap b = new Bootstrap(); 
  6.             b.group(group
  7.                     .channel(NioSocketChannel.class) 
  8.                     .option(ChannelOption.TCP_NODELAY, true
  9.                     .handler(new ChannelInitializer() { 
  10.                         @Override 
  11.                         protected void initChannel(SocketChannel ch) throws Exception { 
  12.                             ch.pipeline().addLast(new StringDecoder()); 
  13.                             ch.pipeline().addLast(new NettyClientHandler()); 
  14.                         } 
  15.                     }); 
  16.             ChannelFuture sync = b.connect("127.0.0.1", 50071).sync(); 
  17.             sync.channel().closeFuture().sync(); 
  18.         } catch (Exception e) { 
  19.             e.printStackTrace(); 
  20.         } finally { 
  21.             group.shutdownGracefully(); 
  22.         } 
  23.     } 
  24.  
  25.     private static class NettyClientHandler extends ChannelInboundHandlerAdapter { 
  26.  
  27.         @Override 
  28.         public void channelActive(ChannelHandlerContext ctx) throws Exception { 
  29.             JSONObject jsonObject = new JSONObject(); 
  30.             jsonObject.put("interfaces""interface=com.study.rpc.test.producer" + 
  31.                     ".HelloService&method=sayHello¶meter=com.study.rpc.test.producer.TestBean"); 
  32.             JSONObject param = new JSONObject(); 
  33.             JSONObject bean = new JSONObject(); 
  34.             bean.put("age", 20); 
  35.             bean.put("name""张三"); 
  36.             param.put("com.study.rpc.test.producer.TestBean", bean); 
  37.             jsonObject.put("parameter", param); 
  38.             jsonObject.put("requestId", 3); 
  39.             System.out.println("发送给服务端JSON为:" + jsonObject.toJSONString()); 
  40.             String msg = jsonObject.toJSONString() + "$$"
  41.             ByteBuf byteBuf = Unpooled.buffer(msg.getBytes().length); 
  42.             byteBuf.writeBytes(msg.getBytes()); 
  43.             ctx.writeAndFlush(byteBuf); 
  44.         } 
  45.  
  46.         @Override 
  47.         public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 
  48.             System.out.println("收到消息:" + msg); 
  49.         } 
  50.     } 

启动之后,看到控制台输出:

  1. 发送给服务端JSON为:{"interfaces":"interface=com.study.rpc.test.producer.HelloService&method=sayHello& 
  2. parameter=com.study.rpc.test.producer.TestBean","requestId":3, 
  3. "parameter":{"com.study.rpc.test.producer.TestBean":{"name":"张三","age":20}}} 
  4.  
  5. 收到消息:{"interfaceMethodIdentify":"interface=com.study.rpc.test.producer.HelloService& 
  6. method=sayHello¶meter=com.study.rpc.test.producer.TestBean","requestId":"3", 
  7. "result":"\"牛逼,我收到了消息:TestBean{name='张三', age=20}\""

Bingo,完美实现了 RPC 的服务提供者。接下来我们只需要实现服务消费者就完成了。

开发服务消费者

服务消费者是同样的处理,我们同样要定义一个消费者的配置:

  1. public class ReferenceConfig{ 
  2.  
  3.     private Class type; 
  4.  
  5.     public ReferenceConfig(Classtype) { 
  6.         this.type = type; 
  7.     } 
  8.  
  9.     public ClassgetType() { 
  10.         return type; 
  11.     } 
  12.  
  13.     public void setType(Classtype) { 
  14.         this.type = type; 
  15.     } 

然后我们是统一入口,在 ApplicationContext 中修改代码:

  1. public ApplicationContext(String registryUrl, ListserviceConfigs, 
  2.                               ListreferenceConfigs, int port) throws Exception { 
  3.         // step 1: 保存服务提供者和消费者 
  4.         this.serviceConfigs = serviceConfigs == null ? new ArrayList<>() : serviceConfigs; 
  5.         this.referenceConfigs = referenceConfigs == null ? new ArrayList<>() : referenceConfigs; 
  6.         // .... 
  7.  
  8.  
  9. private void doRegistry(RegistryInfo registryInfo) throws Exception { 
  10.     for (ServiceConfig config : serviceConfigs) { 
  11.         Class type = config.getType(); 
  12.         registry.register(type, registryInfo); 
  13.         Method[] declaredMethods = type.getDeclaredMethods(); 
  14.         for (Method method : declaredMethods) { 
  15.             String identify = InvokeUtils.buildInterfaceMethodIdentify(type, method); 
  16.             interfaceMethods.put(identify, method); 
  17.         } 
  18.     } 
  19.     for (ReferenceConfig config : referenceConfigs) { 
  20.         ListregistryInfos = registry.fetchRegistry(config.getType()); 
  21.         if (registryInfos != null) { 
  22.             interfacesMethodRegistryList.put(config.getType(), registryInfos); 
  23.             initChannel(registryInfos); 
  24.         } 
  25.     } 

在注册的时候,我们需要将需要消费的接口,通过注册中心抓取出来,所以注册中心要增加一个接口方法:

  1. public interface Registry { 
  2.  
  3.     /** 
  4.      * 将生产者接口注册到注册中心 
  5.      * 
  6.      * @param clazz        类 
  7.      * @param registryInfo 本机的注册信息 
  8.      */ 
  9.     void register(Class clazz, RegistryInfo registryInfo) throws Exception; 
  10.  
  11.     /** 
  12.      * 为服务提供者抓取注册表 
  13.      * 
  14.      * @param clazz 类 
  15.      * @return 服务提供者所在的机器列表 
  16.      */ 
  17.     ListfetchRegistry(Class clazz) throws Exception; 

获取服务提供者的机器列表

具体在 Zookeeper 中的实现如下:

  1. @Override 
  2. public ListfetchRegistry(Class clazz) throws Exception { 
  3.     Method[] declaredMethods = clazz.getDeclaredMethods(); 
  4.     ListregistryInfos = null
  5.     for (Method method : declaredMethods) { 
  6.         String key = InvokeUtils.buildInterfaceMethodIdentify(clazz, method); 
  7.         String path = "/myRPC/" + key
  8.         Stat stat = client.checkExists() 
  9.                 .forPath(path); 
  10.         if (stat == null) { 
  11.             // 这里可以添加watcher来监听变化,这里简化了,没有做这个事情 
  12.             System.out.println("警告:无法找到服务接口:" + path); 
  13.             continue
  14.         } 
  15.         if (registryInfos == null) { 
  16.             byte[] bytes = client.getData().forPath(path); 
  17.             String data = new String(bytes, StandardCharsets.UTF_8); 
  18.             registryInfos = JSONArray.parseArray(data, RegistryInfo.class); 
  19.         } 
  20.     } 
  21.     return registryInfos; 

其实就是去 Zookeeper 获取节点中的数据,得到接口所在的机器信息,获取到的注册信息诸侯,就会调用以下代码:

  1. if (registryInfos != null) { 
  2.     // 保存接口和服务地址 
  3.     interfacesMethodRegistryList.put(config.getType(), registryInfos); 
  4.     // 初始化网络连接 
  5.     initChannel(registryInfos); 
  6. private void initChannel(ListregistryInfos) throws InterruptedException { 
  7.     for (RegistryInfo info : registryInfos) { 
  8.         if (!channels.containsKey(info)) { 
  9.             System.out.println("开始建立连接:" + info.getIp() + ", " + info.getPort()); 
  10.             NettyClient client = new NettyClient(info.getIp(), info.getPort()); 
  11.             client.setMessageCallback(message -> { 
  12.                 // 这里收单服务端返回的消息,先压入队列 
  13.                 RpcResponse response = JSONObject.parseObject(message, RpcResponse.class); 
  14.                 responses.offer(response); 
  15.                 synchronized (ApplicationContext.this) { 
  16.                     ApplicationContext.this.notifyAll(); 
  17.                 } 
  18.             }); 
  19.  
  20.             // 等待连接建立 
  21.             ChannelHandlerContext ctx = client.getCtx(); 
  22.             channels.put(info, ctx); 
  23.         } 
  24.     } 

我们会针对每一个唯一的 RegistryInfo 建立一个连接,然后有这样一段代码:

  1. client.setMessageCallback(message -> { 
  2.     // 这里收单服务端返回的消息,先压入队列 
  3.     RpcResponse response = JSONObject.parseObject(message, RpcResponse.class); 
  4.     responses.offer(response); 
  5.     synchronized (ApplicationContext.this) { 
  6.         ApplicationContext.this.notifyAll(); 
  7.     } 
  8. }); 

设置一个 callback,用于收到消息的时候,回调这里的代码,这部分我们后面再分析。

然后在 client.getCtx() 的时候,同步阻塞直到连接完成,建立好连接后通过,NettyClient 的代码如下:

  1. public class NettyClient { 
  2.  
  3.     private ChannelHandlerContext ctx; 
  4.  
  5.     private MessageCallback messageCallback; 
  6.  
  7.     public NettyClient(String ip, Integer port) { 
  8.         EventLoopGroup group = new NioEventLoopGroup(); 
  9.         try { 
  10.             Bootstrap b = new Bootstrap(); 
  11.             b.group(group
  12.                     .channel(NioSocketChannel.class) 
  13.                     .option(ChannelOption.TCP_NODELAY, true
  14.                     .handler(new ChannelInitializer() { 
  15.                         @Override 
  16.                         protected void initChannel(SocketChannel ch) throws Exception { 
  17.                             ByteBuf delimiter = Unpooled.copiedBuffer("$$".getBytes()); 
  18.                             // 设置按照分隔符“&&”来切分消息,单条消息限制为 1MB 
  19.                             ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024 * 1024, delimiter)); 
  20.                             ch.pipeline().addLast(new StringDecoder()); 
  21.                             ch.pipeline().addLast(new NettyClientHandler()); 
  22.                         } 
  23.                     }); 
  24.             ChannelFuture sync = b.connect(ip, port).sync(); 
  25.         } catch (Exception e) { 
  26.             e.printStackTrace(); 
  27.         } 
  28.     } 
  29.  
  30.     public void setMessageCallback(MessageCallback callback) { 
  31.         this.messageCallback = callback; 
  32.     } 
  33.  
  34.     public ChannelHandlerContext getCtx() throws InterruptedException { 
  35.         System.out.println("等待连接成功..."); 
  36.         if (ctx == null) { 
  37.             synchronized (this) { 
  38.                 wait(); 
  39.             } 
  40.         } 
  41.         return ctx; 
  42.     } 
  43.     private class NettyClientHandler extends ChannelInboundHandlerAdapter { 
  44.         @Override 
  45.         public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 
  46.             try { 
  47.                 String message = (String) msg; 
  48.                 if (messageCallback != null) { 
  49.                     messageCallback.onMessage(message); 
  50.                 } 
  51.             } finally { 
  52.                 ReferenceCountUtil.release(msg); 
  53.             } 
  54.         } 
  55.         @Override 
  56.         public void channelActive(ChannelHandlerContext ctx) throws Exception { 
  57.             NettyClient.this.ctx = ctx; 
  58.             System.out.println("连接成功:" + ctx); 
  59.             synchronized (NettyClient.this) { 
  60.                 NettyClient.this.notifyAll(); 
  61.             } 
  62.         } 
  63.         @Override 
  64.         public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 
  65.             ctx.flush(); 
  66.         } 
  67.         @Override 
  68.         public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 
  69.             cause.printStackTrace(); 
  70.         } 
  71.     } 
  72.     public interface MessageCallback { 
  73.         void onMessage(String message); 
  74.     } 

这里主要是用了 wait() 和 notifyAll() 来实现同步阻塞等待连接建立。建立好连接后,我们保存到集合中:

  1. // 等待连接建立 
  2. ChannelHandlerContext ctx = client.getCtx(); 
  3. channels.put(info, ctx); 

发送请求

好了,到了这里我们为每一个需要消费的接口建立了网络连接,接下来要做的事情就是提供一个接口给用户获取服务提供者实例。

我把这个方法写在 ApplicationContext 中:

  1. /** 
  2.  * 负责生成requestId的类 
  3.  */ 
  4. private LongAdder requestIdWorker = new LongAdder(); 
  5.  
  6. /** 
  7.  * 获取调用服务 
  8.  */ 
  9. @SuppressWarnings("unchecked"
  10. publicT getService(Classclazz){ 
  11.     return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{clazz}, new InvocationHandler() { 
  12.         @Override 
  13.         public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
  14.             String methodName = method.getName(); 
  15.             if ("equals".equals(methodName) || "hashCode".equals(methodName)) { 
  16.                 throw new IllegalAccessException("不能访问" + methodName + "方法"); 
  17.             } 
  18.             if ("toString".equals(methodName)) { 
  19.                 return clazz.getName() + "#" + methodName; 
  20.             } 
  21.  
  22.  
  23.             // step 1: 获取服务地址列表 
  24.             ListregistryInfos = interfacesMethodRegistryList.get(clazz); 
  25.  
  26.             if (registryInfos == null) { 
  27.                 throw new RuntimeException("无法找到服务提供者"); 
  28.             } 
  29.  
  30.             // step 2: 负载均衡 
  31.             RegistryInfo registryInfo = loadBalancer.choose(registryInfos); 
  32.  
  33.  
  34.             ChannelHandlerContext ctx = channels.get(registryInfo); 
  35.             String identify = InvokeUtils.buildInterfaceMethodIdentify(clazz, method); 
  36.             String requestId; 
  37.             synchronized (ApplicationContext.this) { 
  38.                 requestIdWorker.increment(); 
  39.                 requestId = String.valueOf(requestIdWorker.longValue()); 
  40.             } 
  41.             Invoker invoker = new DefaultInvoker(method.getReturnType(), ctx, requestId, identify); 
  42.             inProgressInvoker.put(identify + "#" + requestId, invoker); 
  43.             return invoker.invoke(args); 
  44.         } 
  45.     }); 

这里主要是通过动态代理来实现的,首先通过 class 来获取对应的机器列表,接着通过 loadBalancer 来选择一个机器。

这个 LoaderBalance 是一个接口:

  1. public interface LoadBalancer { 
  2.  
  3.     /** 
  4.      * 选择一个生产者 
  5.      * 
  6.      * @param registryInfos 生产者列表 
  7.      * @return 选中的生产者 
  8.      */ 
  9.     RegistryInfo choose(ListregistryInfos); 
  10.  

在 ApplicationContext 初始化的时候可以选择不同的实现,我这里主要实现了一个简单的随机算法(后续可以拓展为其他的,比如 RoundRobin 之类的):

  1. public class RandomLoadbalancer implements LoadBalancer { 
  2.     @Override 
  3.     public RegistryInfo choose(ListregistryInfos){ 
  4.         Random random = new Random(); 
  5.         int index = random.nextInt(registryInfos.size()); 
  6.         return registryInfos.get(index); 
  7.     } 

接着构造接口方法的唯一标识 identify,还有一个 requestId。为什么需要一个 requestId 呢?

这是因为我们在处理响应的时候,需要找到某个响应是对应的哪个请求,但是仅仅使用 identify 是不行的,因为我们同一个应用程序中可能会有多个线程同时调用同一个接口的同一个方法,这样的 identify 是相同的。

所以我们需要用 identify+requestId 的方式来判断,reqeustId 是一个自增的 LongAddr。服务端在响应的时候会将 requestId 返回。

接着我们构造了一个 Invoker,把它放入 inProgressInvoker 的集合中。调用了其 invoke 方法:

  1. Invoker invoker = new DefaultInvoker(method.getReturnType(), ctx, requestId, identify); 
  2. inProgressInvoker.put(identify + "#" + requestId, invoker); 
  3. // 阻塞等待结果 
  4. return invoker.invoke(args); 
  5.  
  6.  
  7.  
  8. public class DefaultInvokerimplements Invoker{ 
  9.  
  10.     private ChannelHandlerContext ctx; 
  11.     private String requestId; 
  12.     private String identify; 
  13.     private ClassreturnType; 
  14.  
  15.     private T result; 
  16.  
  17.     DefaultInvoker(ClassreturnType, ChannelHandlerContext ctx, String requestId, String identify){ 
  18.         this.returnType = returnType; 
  19.         this.ctx = ctx; 
  20.         this.requestId = requestId; 
  21.         this.identify = identify; 
  22.     } 
  23.  
  24.     @SuppressWarnings("unckecked"
  25.     @Override 
  26.     public T invoke(Object[] args) { 
  27.         JSONObject jsonObject = new JSONObject(); 
  28.         jsonObject.put("interfaces", identify); 
  29.         JSONObject param = new JSONObject(); 
  30.         if (args != null) { 
  31.             for (Object obj : args) { 
  32.                 param.put(obj.getClass().getName(), obj); 
  33.             } 
  34.         } 
  35.         jsonObject.put("parameter", param); 
  36.         jsonObject.put("requestId", requestId); 
  37.         System.out.println("发送给服务端JSON为:" + jsonObject.toJSONString()); 
  38.         String msg = jsonObject.toJSONString() + "$$"
  39.         ByteBuf byteBuf = Unpooled.buffer(msg.getBytes().length); 
  40.         byteBuf.writeBytes(msg.getBytes()); 
  41.         ctx.writeAndFlush(byteBuf); 
  42.         waitForResult(); 
  43.         return result; 
  44.     } 
  45.  
  46.     @Override 
  47.     public void setResult(String result) { 
  48.         synchronized (this) { 
  49.             this.result = JSONObject.parseObject(result, returnType); 
  50.             notifyAll(); 
  51.         } 
  52.     } 
  53.  
  54.  
  55.     private void waitForResult() { 
  56.         synchronized (this) { 
  57.             try { 
  58.                 wait(); 
  59.             } catch (InterruptedException e) { 
  60.                 e.printStackTrace(); 
  61.             } 
  62.         } 
  63.     } 

我们可以看到调用 Invoker 的 invoke 方法之后,会运行到 waitForResult() 这里,这里已经把请求通过网络发送出去了,但是就会被卡住。

这是因为我们的网络请求的结果不是同步返回的,有可能是客户端同时发起很多个请求,所以我们不可能在这里让他同步阻塞等待的。

接受响应

那么对于服务消费者而言,把请求发送出去但是卡住了,这个时候当服务端处理完之后,会把消息返回给客户端。

返回的入口在 NettyClient 的 onChannelRead 中:

  1. @Override 
  2. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { 
  3.     try { 
  4.         String message = (String) msg; 
  5.         if (messageCallback != null) { 
  6.             messageCallback.onMessage(message); 
  7.         } 
  8.     } finally { 
  9.         ReferenceCountUtil.release(msg); 
  10.     } 

这里通过 callback 回调出去。是否还记的我们在初始化 NettyClient 的时候,会设置一个 callback?

  1. /** 
  2.  * 响应队列 
  3.  */ 
  4. private ConcurrentLinkedQueueresponses = new ConcurrentLinkedQueue<>(); 
  5.  
  6.  
  7. client.setMessageCallback(message -> { 
  8.     // 这里收单服务端返回的消息,先压入队列 
  9.     RpcResponse response = JSONObject.parseObject(message, RpcResponse.class); 
  10.     responses.offer(response); 
  11.     synchronized (ApplicationContext.this) { 
  12.         ApplicationContext.this.notifyAll(); 
  13.     } 
  14. }); 

这里接受消息之后,解析成为一个 RpcResponse 对象,然后压入 responses 队列中,这样我们就把所有的请求响应放入队列中。

但是这样一来,我们应该怎么把响应结果返回给调用的地方呢?

我们可以这样做:起一个或多个后台线程,然后从队列中拿出响应,然后根据响应从我们之前保存的 inProcessInvoker 中找出对应的 Invoker,然后把结果返回回去。

  1. public ApplicationContext(....){ 
  2.  
  3.     //..... 
  4.  
  5.     // step 5:启动处理响应的processor 
  6.     initProcessor(); 
  7.  
  8.  
  9. private void initProcessor() { 
  10.     // 事实上,这里可以通过配置文件读取,启动多少个processor 
  11.     int num = 3; 
  12.     processors = new ResponseProcessor[num]; 
  13.     for (int i = 0; i < 3; i++) { 
  14.         processors[i] = createProcessor(i); 
  15.     } 
  16.  
  17. /** 
  18.  * 处理响应的线程 
  19.  */ 
  20. private class ResponseProcessor extends Thread { 
  21.     @Override 
  22.     public void run() { 
  23.         System.out.println("启动响应处理线程:" + getName()); 
  24.         while (true) { 
  25.             // 多个线程在这里获取响应,只有一个成功 
  26.             RpcResponse response = responses.poll(); 
  27.             if (response == null) { 
  28.                 try { 
  29.                     synchronized (ApplicationContext.this) { 
  30.                         // 如果没有响应,先休眠 
  31.                         ApplicationContext.this.wait(); 
  32.                     } 
  33.                 } catch (InterruptedException e) { 
  34.                     e.printStackTrace(); 
  35.                 } 
  36.             } else { 
  37.                 System.out.println("收到一个响应:" + response); 
  38.                 String interfaceMethodIdentify = response.getInterfaceMethodIdentify(); 
  39.                 String requestId = response.getRequestId(); 
  40.                 String key = interfaceMethodIdentify + "#" + requestId; 
  41.                 Invoker invoker = inProgressInvoker.remove(key); 
  42.                 invoker.setResult(response.getResult()); 
  43.             } 
  44.         } 
  45.     } 

这里面如果从队列中拿不到数据,就会调用 wait() 方法等待。这里需要注意的是,在 callbak 中获取到响应的时候我们是会调用 notifyAll() 来唤醒这里的线程的:

  1. responses.offer(response); 
  2. synchronized (ApplicationContext.this) { 
  3.     ApplicationContext.this.notifyAll(); 

这里被唤醒之后,就会有多个线程去争抢那个响应,因为队列是线程安全的,所以这里多个线程可以获取到响应结果。

接着拿到结果之后,通过 identify+requestId 构造成唯一的请求标识,从 inProgressInvoker 中获取对应的 invoker,然后通过 setResult 将结果设置进去:

  1. String key = interfaceMethodIdentify + "#" + requestId; 
  2. Invoker invoker = inProgressInvoker.remove(key); 
  3. invoker.setResult(response.getResult()); 
  4.  
  5.  
  6. @Override 
  7. public void setResult(String result) { 
  8.     synchronized (this) { 
  9.         this.result = JSONObject.parseObject(result, returnType); 
  10.         notifyAll(); 
  11.     } 

这里设置进去之后,就会将结果用 json 反序列化成为用户需要的结果,然后调用其 notifyAll 方法唤醒 invoke 方法被阻塞的线程:

  1. @SuppressWarnings("unckecked"
  2.     @Override 
  3.     public T invoke(Object[] args) { 
  4.         JSONObject jsonObject = new JSONObject(); 
  5.         jsonObject.put("interfaces", identify); 
  6.         JSONObject param = new JSONObject(); 
  7.         if (args != null) { 
  8.             for (Object obj : args) { 
  9.                 param.put(obj.getClass().getName(), obj); 
  10.             } 
  11.         } 
  12.         jsonObject.put("parameter", param); 
  13.         jsonObject.put("requestId", requestId); 
  14.         System.out.println("发送给服务端JSON为:" + jsonObject.toJSONString()); 
  15.         String msg = jsonObject.toJSONString() + NettyServer.DELIMITER; 
  16.         ByteBuf byteBuf = Unpooled.buffer(msg.getBytes().length); 
  17.         byteBuf.writeBytes(msg.getBytes()); 
  18.         ctx.writeAndFlush(byteBuf); 
  19.         // 这里被唤醒 
  20.         waitForResult(); 
  21.         return result; 
  22.     } 

然后就可以返回结果了,返回的结果就会返回给用户了。

整体测试

到了这里我们的生产者和消费者的代码都写完了,我们来整体测试一遍。生产者的代码是和之前的一致的:

  1. public class TestProducer { 
  2.     public static void main(String[] args) throws Exception { 
  3.         String connectionString = "zookeeper://localhost1:2181,localhost2:2182,localhost3:2181"
  4.         HelloService service = new HelloServiceImpl(); 
  5.         ServiceConfig config = new ServiceConfig<>(HelloService.class, service); 
  6.         ListserviceConfigList = new ArrayList<>(); 
  7.         serviceConfigList.add(config); 
  8.         ApplicationContext ctx = new ApplicationContext(connectionString, serviceConfigList, null, 50071); 
  9.     } 
  10.  

消费者测试代码:

  1. public class TestConsumer { 
  2.  
  3.     public static void main(String[] args) throws Exception { 
  4.         String connectionString = "zookeeper://localhost1:2181,localhost2:2182,localhost3:2181"
  5.         ReferenceConfigconfig = new ReferenceConfig<>(HelloService.class); 
  6.         ApplicationContext ctx = new ApplicationContext(connectionString, null, Collections.singletonList(config), 
  7.                 50070); 
  8.         HelloService helloService = ctx.getService(HelloService.class); 
  9.         System.out.println("sayHello(TestBean)结果为:" + helloService.sayHello(new TestBean("张三", 20))); 
  10.     } 

接着启动生产者,然后启动消费者。生产者得到的日志如下:

  1. Zookeeper Client初始化完毕...... 
  2. 注册到注册中心,路径为:【/myRPC/interface=com.study.rpc.test.producer.HelloService& 
  3. method=sayHello¶meter=com.study.rpc.test.producer.TestBean】 
  4. 信息为:RegistryInfo{hostname='localhost', ip='192.168.16.7', port=50071} 
  5. 启动NettyService,端口为:50071 
  6. 启动响应处理线程:Response-processor-0 
  7. 启动响应处理线程:Response-processor-2 
  8. 启动响应处理线程:Response-processor-1 
  9. 接收到消息:{"interfaces":"interface=com.study.rpc.test.producer.HelloService& 
  10. method=sayHello¶meter=com.study.rpc.test.producer.TestBean","requestId":"1", 
  11. "parameter":{"com.study.rpc.test.producer.TestBean":{"age":20,"name":"张三"}}} 
  12.  
  13. 响应给客户端:{"interfaceMethodIdentify":"interface=com.study.rpc.test.producer.HelloService& 
  14. method=sayHello¶meter=com.study.rpc.test.producer.TestBean","requestId":"1", 
  15. "result":"\"牛逼,我收到了消息:TestBean{name='张三', age=20}\""

消费者得到的日志为:

  1. Zookeeper Client初始化完毕...... 
  2. 开始建立连接:192.168.16.7, 50071 
  3. 等待连接成功... 
  4. 启动响应处理线程:Response-processor-1 
  5. 启动响应处理线程:Response-processor-0 
  6. 启动响应处理线程:Response-processor-2 
  7. 连接成功:ChannelHandlerContext(NettyClient$NettyClientHandler#0, 
  8. [id: 0xb7a59701, L:/192.168.16.7:58354 - R:/192.168.16.7:50071]) 
  9.  
  10. 发送给服务端JSON为:{"interfaces":"interface=com.study.rpc.test.producer.HelloService& 
  11. method=sayHello¶meter=com.study.rpc.test.producer.TestBean","requestId":"1", 
  12. "parameter":{"com.study.rpc.test.producer.TestBean":{"age":20,"name":"张三"}}} 
  13.  
  14. 收到一个响应:RpcResponse{result='"牛逼,我收到了消息:TestBean{name='张三', age=20}"'
  15. interfaceMethodIdentify='interface=com.study.rpc.test.producer.HelloService& 
  16. method=sayHello¶meter=com.study.rpc.test.producer.TestBean', requestId='1'} 
  17. sayHello(TestBean)结果为:牛逼,我收到了消息:TestBean{name='张三', age=20} 

总结

通过完成这个 RPC 框架,大家应该会大致对 RPC 的实现原理有个感性的认识。

这里总结一下特性:

  • 支持多种注册中心,可配置。(虽然只实现了 Zookeeper,但是我们拓展是非常简单的)
  • 支持负载均衡。

当然了还有非常多的不足之处,这是无可否认的,随意写出来的框架和工业级使用的框架比较还是不一样。

我这里列举一些不完美的地方(有兴趣的可以搞搞):

  • 实现序列化框架的拓展,多种序列化供用户选择。
  • 网络请求错误处理,这里实现非常简陋,健壮性很差。
  • 注册中心不支持故障感知和自动恢复。
  • 调用监控,性能指标。

作者:王码农

编辑:陶家龙

出处:转载自公众号石杉的架构笔记(ID:shishan100)

 

责任编辑:武晓燕 来源: 石杉的架构笔记
相关推荐

2019-06-17 08:21:06

RPC框架服务

2020-11-02 08:19:18

RPC框架Java

2020-12-07 08:43:55

代码软件开发

2022-03-01 11:38:51

RPC框架后端

2021-02-20 09:45:02

RPC框架Java

2022-11-07 18:36:03

组件RPC框架

2021-04-29 23:45:07

函数式接口可用性

2024-01-02 12:17:44

Go传统远程

2018-09-18 09:38:11

RPC远程调用网络通信

2012-01-04 13:55:23

Canvas

2017-06-08 15:53:38

PythonWeb框架

2015-10-12 16:45:26

NodeWeb应用框架

2023-02-13 00:18:22

前端库框架集合

2016-12-20 13:55:52

2022-11-10 09:28:40

框架开发

2016-11-29 13:31:52

JavaScriptsetTimeout定时执行

2015-04-29 10:02:45

框架如何写框架框架步骤

2022-03-07 05:53:41

线程CPU代码

2015-08-07 10:51:00

Android App第一个

2020-01-09 11:11:35

RPC框架调用远程
点赞
收藏

51CTO技术栈公众号