首页 > 编程知识 正文

netty怎么样,那些框架底层用到netty

时间:2023-05-05 21:52:54 阅读:25226 作者:1734

Netty框架模型NIO的类库和API繁琐,难以使用:需要熟练使用选择器、服务器套接字、通道套接字、字节缓冲器等。 开发工作量和难度非常高。 例如,客户端面临断开、重新连接、网络闪存断开、心跳处理、半数据包读写、网络拥塞、异常流处理等。

Netty很好地封装了JDK拥有的NIO的API,解决了上述问题。 Netty还具有高性能、高吞吐量、低延迟、减少资源消耗以及最大限度地减少不必要的内存复制等优点。

Netty目前使用4.x,5.x版已过时。 Netty 4.x需要JDK 6或更高版本的支持。

Netty使用场景:

1 )互联网行业)在分布式系统中,各节点之间需要远程服务调用,高性能的RPC框架是必不可少的。 Netty作为异步、高性能的通信框架,经常被这些RPC框架用作主干通信组件。 一种典型的应用是蚂蚁分布式服务框架Dubbo的RPC框架使用Dubbo协议进行节点间通信,Dubbo协议默认使用Netty作为基本通信组件并用于实现。 各进程节点之间的内部通信。 Rocketmq的基础也使用Netty作为基础通信组件。

2 )游戏行业)无论是手游服务端还是大型网络游戏,Java语言都得到越来越广泛的应用。 Netty是一个高性能的核心通信组件,它本身提供TCP/UDP和HTTP协议栈。

3 )大数据领域:经典的Hadoop高性能通信和串行化组件Avro的RPC框架默认使用Netty进行交叉点通信,其Netty Service是Netty框架的辅助封装

Netty线程模型

模型解释

Netty将两个线程池、boss组和work组抽象。 Boss Group用于处理接受事件,而Work Group用于处理读取和写入事件。 Boss Group和Work Group都属于EventLoopGroup。 NioEventLoopGroup相当于包含多个事件循环线程的事件循环线程组,每个事件循环线程都是NioEventLoop。 对于每个NioEventLoop,选择器用于接收绑定的通道总线NioEventLoop的处理流为以下:

执行accpet操作并返回到SocketChanel

b .将此套接字通道注册到某个工作通告程序选择器

c .处理任务队列的任务,即runAllTasksWork NioEventLoop的处理流为以下:

a .轮询在此Loop Seletor中注册的所有套接字通道的读取/写入事件

处理读取/写入事件

c.runAllTasks处理任务队列TaskQueue中的任务。 一些耗时的业务处理通常可以放入Netty中实战编写聊天室程序。 服务端具备在线检测、聊天内容群发等。 Netty大大简化了NIO编程,开发人员经常编写ChannelHandle逻辑进行业务处理

服务端代码服务器

package com.hldxrz.chat; import io.net ty.bootstrap.server bootstrap; import io.net ty.channel.channel future; import io.net ty.channel.channel initializer; import io.net ty.channel.eventloopgroup; import io.net ty.channel.nio.nioeventloopgroup; import io.net ty.channel.socket.socket channel; import io.net ty.channel.socket.nio.nioserversocketchannel; import io.net ty.handler.codec.string.string decoder; import io.net ty.handler.codec.string.string encoder;/* * @ class name chat server * @ description todo * @ author : Zhang lianzhong * @ date 2020/11/2210:13下午* @版本1 . public class chat server { public void openserver (导入) ) serverbootstrapbootstrap=new server bootstrap ); eventloopgroupboss=newnioeventloopgroup (1; //create boss group,threadpoolsizeis1eventloopgroupwork=newnioeventloopgroup (5; //create work group,threadpoolsizeis5bootstrap.group (boss,wo ) ) ) ) ) 65 )

rk); //组合netty组件 //配置handle组件 bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("encoder",new StringEncoder()); ch.pipeline().addLast("decoder",new StringDecoder()); ch.pipeline().addLast(new ServerChanelHandle()); } }); bootstrap.channel(NioServerSocketChannel.class); try{ ChannelFuture channel = bootstrap.bind(port).sync(); System.out.println(("服务端已启动,绑定端口:" + port)); channel.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); }finally { boss.shutdownGracefully(); work.shutdownGracefully(); } } public static void main(String[] args){ ChatServer server = new ChatServer(); server.openServer(8090); }}

服务端ChannelHandle

package com.hldxrz.chat;import io.netty.channel.Channel;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;import io.netty.channel.group.ChannelGroup;import io.netty.channel.group.DefaultChannelGroup;import io.netty.util.concurrent.GlobalEventExecutor;/** * @ClassName ServerChanelHandle * @Description TODO * @Author:Zhang Lianzhong * @Date 2020/11/22 10:21 下午 * @Version 1.0 **/public class ServerChanelHandle extends SimpleChannelInboundHandler { //必须定义为类成员变量。每个客户端连接时,都会new ChatServerHandler。static保证数据共享 public static ChannelGroup cg = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { Channel ch = ctx.channel(); for(Channel chanel: cg){ chanel.writeAndFlush(ch.remoteAddress()+"进来啦!"); } cg.add(ch); } /** * 上线处理 * @param ctx * @throws Exception */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); for(Channel ch: cg){ ch.writeAndFlush(channel.remoteAddress()+"上线啦"); } } @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel channel = ctx.channel(); for(Channel ch: cg){ if(channel ==ch){ ch.writeAndFlush("我说"+msg); }else { ch.writeAndFlush(channel.remoteAddress()+"说:"+msg); } } } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); cg.remove(channel); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); String customerAddress = channel.remoteAddress().toString(); for(Channel ch:cg){ ch.writeAndFlush("客户端" + customerAddress + "下线了!"); } }}

客户端Client

package com.hldxrz.chat;import io.netty.bootstrap.Bootstrap;import io.netty.channel.Channel;import io.netty.channel.ChannelFuture;import io.netty.channel.ChannelInitializer;import io.netty.channel.EventLoopGroup;import io.netty.channel.nio.NioEventLoopGroup;import io.netty.channel.socket.SocketChannel;import io.netty.channel.socket.nio.NioSocketChannel;import io.netty.handler.codec.string.StringDecoder;import io.netty.handler.codec.string.StringEncoder;import java.util.Scanner;/** * @ClassName ChatClient * @Description TODO * @Author:Zhang Lianzhong * @Date 2020/11/22 10:54 下午 * @Version 1.0 **/public class ChatClient implements Runnable{ private String serverIP; private int port; public ChatClient(String serverIp,int port ){ this.serverIP = serverIp; this.port = port; } @Override public void run() { Bootstrap bootstrap = new Bootstrap(); EventLoopGroup work = new NioEventLoopGroup(1); bootstrap.group(work); bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("encode",new StringEncoder()); ch.pipeline().addLast("decode",new StringDecoder()); ch.pipeline().addLast(new ClientChanelHandle()); } }); bootstrap.channel(NioSocketChannel.class); ChannelFuture channelFuture = bootstrap.connect(serverIP,port); Channel channel = channelFuture.channel(); Scanner scanner = new Scanner(System.in); while(scanner.hasNext()){ String sendMsg = scanner.nextLine(); channel.writeAndFlush(sendMsg); } work.shutdownGracefully(); } public static void main(String[] args){ new Thread(new ChatClient("127.0.0.1",8090)).start(); }}

客户端ChannelHandle

package com.hldxrz.chat;import io.netty.channel.ChannelHandlerContext;import io.netty.channel.SimpleChannelInboundHandler;/** * @ClassName ClientChanelHandle * @Description TODO * @Author:Zhang Lianzhong * @Date 2020/11/22 11:08 下午 * @Version 1.0 **/public class ClientChanelHandle extends SimpleChannelInboundHandler { @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { System.out.println(msg); }} 运行效果



版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。