guide-rpc-framework 源码学习

时间:2022-07-24
本文章向大家介绍guide-rpc-framework 源码学习,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

老婆:你为什么跪着写文章?

我:朋友圈有个程序猿花了2个月的头发写了一个 RPC 框架示例(代码地址:https://github.com/Snailclimb/guide-rpc-framework),刚刚下载到本地看着看着就【手动狗头】。

GitHub 上的开源项目,我最喜欢的那种 star 多于 1k 的,其次是 README.MD 有文字带图片的。前者,是拥有千名程序员的点[jia]赞[xing];后者,是作者走心了。guide-rpc-framework 新鲜出炉,star 较少属于后者。


项目模块

guide-rpc-framwork 是基于 Netty、Kyro、Zookeeper 实现的 RPC 框架。

  • example-client 示例客户端
  • example-service 示例服务端
  • hello-service-api 存放服务接口
  • rpc-framework-common 实例对象、枚举、工具类
  • rpc-framework-simple RPC 框架核心实现类

项目模块是非常简练的,如果换成是我这种强迫症患者来分的话,还是会增加一个 rpc-framework-parent 模块(虽然 rpc-framework-parent 这个模块没什么用处)。

REAMDE.md 有完整的教程(包括 Zookeeper 安装等等),这里就不再赘述了。还没有项目经验的新手,可以 fork 参与开源项目开发哦。


RPC 核心框架

RPC-FRAMEWORK-COMMON

简洁干练的 common 工程,约定了 RPC 错误信息、响应错误码枚举,RPC、序列化的自定义错误,单例工厂类,线程池、zookeeper 工具类。

RPC-FRAMEWORK-SERVICE

RPC 框架的核心实现类。保存服务端注册的实例,并提供动态代理的方式用于客户端发送请求(socket、netty 方式)到服务端。

同时,提供了 Zookeeper 的服务注册、kyro 序列化与反序列化的能力。


示例使用

EXAMPLE-SERVER

RPC 服务端,使用 netty、socket 两种注册方式提供服务。

public static void main(String[] args) {
    HelloService helloService = new HelloServiceImpl();
    NettyServer nettyServer = new NettyServer("127.0.0.1", 9999);
    nettyServer.publishService(helloService, HelloService.class);
}
public static void main(String[] args) {
    HelloService helloService = new HelloServiceImpl();
    SocketRpcServer socketRpcServer = new SocketRpcServer("127.0.0.1", 8080);
    socketRpcServer.publishService(helloService, HelloService.class);
}

EXAMPLE-CLIENT

RPC 客户端,使用 netty、socket 两种客户端方式发送请求到服务端。

public static void main(String[] args) {
    ClientTransport rpcClient = new NettyClientTransport();
    RpcClientProxy rpcClientProxy = new RpcClientProxy(rpcClient);
    HelloService helloService = rpcClientProxy.getProxy(HelloService.class);
    String hello = helloService.hello(new Hello("111", "222"));
    //如需使用 assert 断言,需要在 VM options 添加参数:-ea
    assert "Hello description is 222".equals(hello);
    for (int i = 0; i < 50; i++) {
        String des = helloService.hello(new Hello("111", "~~~" + i));
        System.out.println(des);
    }
}
public static void main(String[] args) {
    ClientTransport clientTransport = new SocketRpcClient();
    RpcClientProxy rpcClientProxy = new RpcClientProxy(clientTransport);
    HelloService helloService = rpcClientProxy.getProxy(HelloService.class);
    String hello = helloService.hello(new Hello("111", "222"));
    System.out.println(hello);
}

小结

写到这里,腿脚已经麻木了。有的程序员两个月能产出优质的框架代码,而我沉迷于猛男捡树枝不能自拔

这个周末,又一次成功“强迫”自己学习。