一 Netty简单RPC调用
1.1 RPC基本介绍
- RPC(Remote Procedure Call),远程过程调用,是一个计算机通信协议。该协议允许运行于一台计算机的程序调用另一台计算机的子程序,而程序员无需额外地为这个交互作用编程
- 两个或多个应用程序都分布在不同的服务器上,它们之间的调用都像是本地方法调用一样(如图)

- 常见的 RPC 框架有: 比较知名的如阿里的Dubbo、google的gRPC、Go语言的rpcx、Apache的thrift, Spring 旗下的 Spring Cloud。
RPC调用流程:
在RPC 中, Client 叫服务消费者,Server 叫服务提供者
PRC调用流程说明
- 服务消费方(client)以本地调用方式调用服务
- client stub 接收到调用后,负责将方法、参数等封装成能够进行网络传输的消息体
- client stub 将消息进行编码并发送到服务端
- server stub 收到消息后进行解码
- server stub 根据解码结果调用本地的服务
- 本地服务执行并将结果返回给server stub
- server stub 将返回导入结果进行编码并发送至消费方
- client stub 接收到消息并进行解码
- 服务消费方(client)得到结果

小结:RPC 的目标就是将 2-8 这些步骤都封装起来,用户无需关心这些细节,可以像调用本地方法一样即可完成远程服务调用。
1.2 代码示例
服务接口:
public interface HelloService {String hello(String message);}
服务端服务接口实现类:
public class HelloServiceImpl implements HelloService {@Overridepublic String hello(String message) {System.out.println("收到客户端消息=" + message);//根据 message 返回不同的结果if(message != null) {return "你好客户端,我已经收到你的消息【" + message + "】";} else {return "你好客户端,我已经收到你的消息。";}}}
服务端初始化Netty:
public class NettyServer {public static void startServer(String hostName, int port) {startServer0(hostName, port);}private static void startServer0(String hostname, int port) {NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);NioEventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new StringDecoder());pipeline.addLast(new StringEncoder());pipeline.addLast(new NettyServerHandler()); //业务处理器}});ChannelFuture channelFuture = serverBootstrap.bind(hostname,port).sync();System.out.println("服务提供方开始运行");channelFuture.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}}
服务端Handler:
public class NettyServerHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//获取客户端发送的消息,并调用服务System.out.println("msg=" + msg);//客户端在调用服务器的api 时,我们需要定义一个协议//比如要求,每次发消息时,都必须以某个字符串开头 "HelloService#hello#你好"if (msg.toString().startsWith("HelloService#hello#")) {String result = new HelloServiceImpl().hello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));ctx.writeAndFlush(result);}}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();}}
Netty客户端
public class NettyClient {//创建一个线程池private static ExecutorService executor= Executors.newFixedThreadPool(5);private static NettyClientHandler client;//编写方法,使用代理模式,获取一个代理对象public Object getBean(final Class<?> serviceClass, final String providerName) {return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass},(proxy, method, args) -> {System.out.println("代理被调用");if (client == null)initClient();//设置要发给服务器端的信息client.setPara(providerName + args[0]);return executor.submit(client).get();});}//初始化客户端private static void initClient() {client = new NettyClientHandler();//创建EventLoopGroupNioEventLoopGroup group = new NioEventLoopGroup();try {Bootstrap bootstrap = new Bootstrap();bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();pipeline.addLast(new StringDecoder());pipeline.addLast(new StringEncoder());pipeline.addLast(client);}});ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 7000).sync();} catch (InterruptedException e) {e.printStackTrace();}}}
客户端Handler
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {private ChannelHandlerContext context; //上下文private String result; //返回的结果private String para; //客户端调用方法时,传入的参数//与服务端创建连接后调用@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("通道连接成功");context = ctx; //因为我们在其他方法会使用到 ctx}@Overridepublic synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {result = msg.toString();notify(); //唤醒等待的线程}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {cause.printStackTrace();ctx.close();}//被代理对象的调用,真正发送数据给服务器,发送完后就阻塞,等待被唤醒(channelRead)@Overridepublic synchronized Object call() throws Exception {System.out.println("线程被调用-----");context.writeAndFlush(para);//进行waitwait(); //等待 channelRead 获取到服务器的结果后,进行唤醒。return result; //服务方返回的结果}public void setPara(String para){this.para = para;}}
客户端启动并调用远程方法:
public class ClientBootStrap {//这里定义协议头public static final String providerName = "HelloService#hello#";public static void main(String[] args) throws InterruptedException {//创建一个消费者NettyClient customer = new NettyClient();//创建代理对象HelloService service = (HelloService) customer.getBean(HelloService.class, providerName);//通过代理对象调用服务提供者的方法String res = service.hello("你好 Dubbo");System.out.println("调用的结果,res = " + res);Thread.sleep(2000);}}
二 总结
一个简单的rpc还是很好实现的, 例如A系统搞个HelloService类 提供一个方法,如果B系统想去调用
A系统的接口,肯定需要走网络,因为我们模仿dubbo,像本地一样的调用,那么我们B系统应该这样做。
B系统
- 拷贝HelloService一份接口
- 动态代理该放类,在方法里加入远程调用A系统的逻辑
- 然后返回远程调用的结果
A系统:
- 接受到B系统的请求,并且根据请求参数判断是哪个实现类的接口,然后调用该接口的本地方法,获取返回值。
- 将返回值返回给B系统
