当前位置: 首页 > article >正文

Netty22——用Netty实现RPC

一、RPC介绍

 RPC(Remote Procedure Call)— 远程过程调用,是一个计算机通信协议。该协议允许运行于一台计算机的程序调用另一台计算机的子程序, 而程序员无需额外地为这个交互编程。两个或多个应用程序分布在不同的服务器上,它们之间的调用像是本地方法调用一样。
在这里插入图片描述
 常见的 RPC 框架有:阿里的Dubbo、google的gRPC、Go语言的rpcx、 Apache的thrift,以及Spring 旗下的 Spring Cloud。
在这里插入图片描述
 在RPC 中, Client 叫服务消费者,Server 叫服务提供者。调用流程如下:
  ①服务消费方(client)以本地调用方式调用服务
  ②client stub 接收到调用后负责将方法、参数等封装成能够进行网络传输的消息体
  ③client stub 将消息进行编码并发送到服务端
  ④server stub 收到消息后进行解码
  ⑤server stub 根据解码结果调用本地的服务
  ⑥本地服务执行并将结果返回给 server stub
  ⑦server stub 将返回导入结果进行编码并发送至消费方
  ⑧client stub 接收到消息并进行解码
  ⑨服务消费方(client)得到结果
 RPC 的目标就是将上面 2-8 这些步骤都封装起来,用户无需关心这些细节,可以像调用本地方法一样即可完成远程服务调用。

二、基于Netty实现RPC(模拟dubbo)

 dubbo 底层使用了 Netty 作为网络通讯框架,要求用 Netty 实现一个简单的 RPC 框架。即模仿 dubbo,消费者和提供者约定接口和协议,消费者远程调用提供者的服务,提供者返回一个字符串,消费者打印提供者返回的数据。底层网络通信使用 Netty 4.1.20。

2.1、设计说明

 1、创建一个接口,定义抽象方法。用于消费者和服务提供者之间的约定
 2、创建一个提供者,该类需要监听消费者的请求,并按照约定返回数据
 3、创建一个消费者,该类需要透明的调用自己不存在(未实现)的方法,内部需要使用 Netty 请求提供者返回数据
在这里插入图片描述

2.2、代码实现

 实际开发过程中服务端代码和客户端代码可能在同一个项目中,只不过通过参数控制是服务端还是客户端。

2.2.1 服务端代码

 1、定义一个接口HelloService

// 服务提供者和服务消费者都需要该接口,但只在服务端实现,客户端无需实现
public interface HelloService {String hello(String mes);
}

 2、服务端实现该接口

public class HelloServiceImpl implements HelloService {private static int count = 0;//当有消费方调用该方法时, 就返回一个结果@Overridepublic String hello(String mes) {System.out.println("收到客户端消息=" + mes);//根据mes 返回不同的结果if (mes != null) {return "你好客户端, 我已经收到你的消息 [" + mes + "] 第" + (++count) + " 次";} else {return "你好客户端, 我已经收到你的消息 ";}}
}

 3、服务端核心程序NettyServer

public class NettyServer {// 静态方法:启动服务端public static void startServer(String hostName, int port) {startServer0(hostName, port);}//编写一个方法,完成对NettyServer的初始化和启动private static void startServer0(String hostname, int port) {EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup 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 (Exception e) {e.printStackTrace();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}
}

 4、自定义业务处理器NettyServerHandler

//服务器这边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(ClientBootstrap.providerName)) {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();}
}

 5、服务端ServerBootstrap启动服务端

//ServerBootstrap 会启动一个服务提供者,就是 NettyServer
public class ServerBootstrap {public static void main(String[] args) {NettyServer.startServer("127.0.0.1", 7000);}
}
2.2.2 客户端代码

 1、客户端业务处理器NettyClientHandler

public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {private ChannelHandlerContext context;//上下文private String result; //返回的结果private String para; //客户端调用方法时,传入的参数//与服务器的连接创建后,就会被调用, 这个方法是第一个被调用(1)@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println(" channelActive 被调用  ");context = ctx; //因为我们在其它方法会使用到 ctx}//收到服务器的数据后,调用方法 (4)//@Overridepublic synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {System.out.println(" channelRead 被调用  ");result = msg.toString();notify(); //唤醒等待的线程}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();}//被代理对象调用, 发送数据给服务器,-> wait -> 等待被唤醒(channelRead) -> 返回结果 (3)-》5@Overridepublic synchronized Object call() throws Exception {System.out.println(" call1 被调用  ");context.writeAndFlush(para);//进行waitwait(); //等待channelRead 方法获取到服务器的结果后,唤醒System.out.println(" call2 被调用  ");return result; //服务方返回的结果}//(2)void setPara(String para) {System.out.println(" setPara  ");this.para = para;}
}

 2、客户端初始化程序NettyClient

public class NettyClient {//创建线程池private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());private static NettyClientHandler client;private int count = 0;//编写方法使用代理模式,获取一个代理对象public Object getBean(final Class<?> serivceClass, final String providerName) {return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class<?>[]{serivceClass}, (proxy, method, args) -> {System.out.println("(proxy, method, args) 进入...." + (++count) + " 次");//{}  部分的代码,客户端每调用一次 hello, 就会进入到该代码if (client == null) {initClient();}//设置要发给服务器端的信息//providerName 协议头 args[0] 就是客户端调用api hello(???), 参数client.setPara(providerName + args[0]);return executor.submit(client).get();});}//初始化客户端private static void initClient() {client = new NettyClientHandler();//创建EventLoopGroupNioEventLoopGroup group = new NioEventLoopGroup();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);}});try {// 和服务端建立连接bootstrap.connect("127.0.0.1", 7000).sync();} catch (Exception e) {e.printStackTrace();}}
}

 3、客户端启动和客户端远程方法调用ClientBootstrap

public class ClientBootstrap {//这里定义协议头public static final String providerName = "HelloService#hello#";public static void main(String[] args) throws Exception {//创建一个消费者NettyClient customer = new NettyClient();//创建代理对象HelloService service = (HelloService) customer.getBean(HelloService.class,providerName);for (; ; ) {Thread.sleep(2 * 1000);//通过代理对象调用服务提供者的方法(服务)String res = service.hello("你好 dubbo~");System.out.println("调用的结果 res= " + res);}}
}
http://www.lryc.cn/news/2420931.html

相关文章:

  • word中拼写希腊字母
  • ASP:FileUpload控件(文件上传控件)
  • 查询EI检索号的方法
  • ant学习-使用ant生成jar包
  • 雅虎免费邮箱开通POP3和自动转发的方法
  • gps信号用什么软件测试,gps信号检测软件
  • Access数据库及注入方法
  • JS定时器的用法及示例
  • AI妻子生成器:科技陪伴,情感无限
  • 解决size mismatch for embedding.embed_dict.userid.weight
  • 单片机——LCD1602
  • 移动测试之-流量测试方案
  • Visual Studio 2008 试用版评估期已结束的解决方法
  • 一步步优化JVM七:其他
  • 无法启动计算机上的服务msdtc,MSDTC服务无法启动解决方法
  • 分享116个ASP搜索链接源码,总有一款适合您
  • Hello C++
  • 纳什均衡定义、举例、分类
  • 开启游戏别样体验:《下一站江湖2》风灵月影六十项修改器使用手册
  • ubuntu9.10 软件推荐
  • Oracle DB Time 解读
  • 收集一些有质感、有内涵的网站 (转载)
  • 实时监控系统介绍
  • MapInfo是一种流行的地理信息系统(GIS)软件,它提供了丰富的功能和工具,用于处理、分析和可视化地理空间数据
  • CAN总线学习笔记 | CAN基础知识介绍
  • 2024年最全在线查询默认密码网站--分享_hawel-lutuo默认密码(1),分析网络安全未来几年的发展前景
  • java计算机毕业设计电商网站在线客服(附源码+springboot+开题+论文+部署)
  • 递归和迭代_深究递归和迭代的区别、优缺点及实例对比
  • 网络层 IPV4报文格式
  • 中国网站广告联盟大集合