Netty框架介绍(netty 结构)
ccwgpt 2024-09-17 12:51 42 浏览 0 评论
一 初步了解Netty
Netty是由JBoss公司推出的一个高性能事件驱动型异步非阻塞的IO(NIO)框架。用于建立TCP等底层的连接,基于Netty可以建立高性能的Http服务器。支持HTTP、WebSocket、Protobuf、Binary TCP和UDP。
Netty提供了NIO和BIO(OIO阻塞IO)两种模式处理逻辑,其中NIO主要通过一个BOSS线程处理等待链接的接入,若干个Worker线程(从worder线程池取出一个赋给channel,因为channel持有真正的java网络对象)接过BOSS线程递交过来的Channel进行数据读写并且触发相应的事件传递给pipeline进行数据处理,而BIO(OIO)方式服务器端虽然还是通过一个BOSS线程来处理等待链接的接入,但是客户端还是由主线程直接connect,另外写数据C/S两端都是直接主线程写,而数据读取则是通过一个Worker线程BLOCK方式读取(一直等待,直到读到数据,除非channel关闭)。
总体结构图:(摘自Netty官网)
二 Netty组件
为了更好的理解和进一步深入Netty,我们先总体认识一下Netty中的组件以及在整个框架中如何协调工作的。Netty应用中必不可少的组件:
Bootstrap or ServerBootstrap
EventLoop
EventLoopGroup
ChannelPipeline
Channel
Future or ChannelFuture
ChannelInitializer
ChannelHandler
Bootstrap:一个Netty应用通常由一个Bootstrap开始,它主要作用是配置整个Netty程序,串联起各个组件,ServerBootstrap用于server端,Bootstrap用于client端。
Handler:为了支持各种协议和处理数据的方式,便诞生了Handler组件。Handler主要用来处理各种事件,这里的事件很广泛,比如可以是连接,数据接收,异常,数据转换等。
ChannelInboundHandler:一个最常用的Handler。这个Handler的作用就是处理接收到数据时的事件,也就是说,我们的业务逻辑一般都写在这个Handler里的,ChannelInboundHandler就是用来处理核心业务逻辑的。
ChannelInitializer:当一个链接建立时,我们需要知道怎么来接收或发送数据,当然,我们有各种各样的Handler实现来处理它,那么ChannelInitializer便是用来配置这些Handler,它会提供一个ChannelPipeline并把Handler加入到ChannelPipeline。
ChannelPipeline:一个Netty应用基于ChannelPipeline机制,这种机制需要依赖于EventLoop和EventLoopGroup,因为它们三个都和事件或者事件处理有关。
EventLoop:EventLoop目的是为Channel处理IO操作,一个Channel对应一个EventLop,而一个EventLoop对应一个线程,也就是说,仅有一个线程在负责一个Channel的IO操作。EventLoopGroup会包含多个EventLoop。
Channel:Channel代表了一个Socket链接,或者其它和IO操作相关的组件,它和EventLoop一起用来参与IO处理。
Future:在Netty中所有的IO操作都是异步的,因此,你不能立刻得知消息是否被正确处理,但是我们可以过一会等它执行完成或者直接注册一个监听,具体的实现就是通过Future和ChannelFutures,它们可以注册一个监听,当操作执行成功或失败时监听会自动触发。总之,所有的操作都会返回一个ChannelFuture。
三 Netty处理连接请求和业务逻辑
当一个连接到达,Netty会注册一个channel,然后EventLoopGroup会分配一个EventLoop绑定到这个channel,在这个channel的整个生命周期过程中,都会由绑定的这个EventLoop来为它服务。
四 Netty使用案例
以下例子是使用Netty4.x编写的案例,不详细描述了,直接上代码:
server端:
package com.cn.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.nio.charset.Charset;
public class MyNettyServer {
public static void main(String[] args) {
new MyNettyServer().serverStart();
}
//用于分配处理业务线程的线程组个数
private static final int PARENTGROUPSIZE = Runtime.getRuntime().availableProcessors();
private static final int CHILDGROUPSIZE = PARENTGROUPSIZE*2;
private static final String HOST = "127.0.0.1";
private static final int PORT = 9999;
NioEventLoopGroup parentGroup;
NioEventLoopGroup childGroup;
/**
*服务端启动方法
*/
public void serverStart(){
try {
final ServerBootstrap server = new ServerBootstrap();
parentGroup = new NioEventLoopGroup(PARENTGROUPSIZE);
childGroup = new NioEventLoopGroup(CHILDGROUPSIZE);
server.group(parentGroup, childGroup);//设置线程组
server.channel(NioServerSocketChannel.class);
server.option(ChannelOption.SO_KEEPALIVE,true);//保持连接
server.option(ChannelOption.SO_BACKLOG,1024);
server.option(ChannelOption.TCP_NODELAY,true);
server.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast("frameDecoder",new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4));
channel.pipeline().addLast("frameEncoder",new LengthFieldPrepender(4));
channel.pipeline().addLast("decoder",new StringDecoder(Charset.forName("GBK")));
channel.pipeline().addLast("encoder",new StringEncoder(Charset.forName("GBK")));
channel.pipeline().addLast(new MyServerHandler());
}
});
ChannelFuture future = server.bind(HOST,PORT).sync();
if(future.isSuccess()){
System.out.println("......Netty Server Started......");
}else{
System.out.println("......Netty Server Failed......");
}
future.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally{
this.parentGroup.shutdownGracefully();
this.childGroup.shutdownGracefully();
}
}
}
package com.cn.netty;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
public class MyServerHandler extends SimpleChannelInboundHandler<String>{
/*
*收到消息时调用
*/
@Override
protected void channelRead0(ChannelHandlerContext context, String msg)throws Exception {
System.out.println("server received msg:"+msg);
context.writeAndFlush(new String("客户端你好"));
}
@Override
public void exceptionCaught(ChannelHandlerContext context, Throwable cause)
throws Exception {
cause.printStackTrace();
context.flush();
context.close();
}
}
Client端:
package com.cn.netty;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
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.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.nio.charset.Charset;
public class MyNettyClient {
public static void main(String[] args) {
Channel channel = new MyNettyClient().clientStart();
channel.writeAndFlush(new String("服务器你好"));
}
private static final String HOST = "127.0.0.1";
private static final int PORT = 9999;
public Channel clientStart(){
Channel channel = null;
Bootstrap client = new Bootstrap();
EventLoopGroup group = new NioEventLoopGroup();
try {
client.group(group);
client.channel(NioSocketChannel.class);
client.option(ChannelOption.SO_KEEPALIVE,true);
client.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel)throws Exception {
channel.pipeline().addLast("frameDecoder",new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4));
channel.pipeline().addLast("frameEncoder",new LengthFieldPrepender(4));
//编码格式
channel.pipeline().addLast("encoder",new StringEncoder(Charset.forName("GBK")));
//解码格式
channel.pipeline().addLast("decoder",new StringDecoder(Charset.forName("GBK")));
channel.pipeline().addLast(new MyClientHandler());
}
});
ChannelFuture future = client.connect(HOST, PORT).sync();
if(future.isSuccess()){
System.out.println("......netty client started......");
}
channel = future.channel();
} catch (InterruptedException e) {
e.printStackTrace();
}
return channel;
}
}
packagecom.cn.netty;
importio.netty.channel.ChannelHandlerContext;
importio.netty.channel.SimpleChannelInboundHandler;
publicclassMyClientHandlerextendsSimpleChannelInboundHandler<String>{
/*
*收到消息时调用
*/
@Override
protectedvoidchannelRead0(ChannelHandlerContext context, String msg)throwsException {
System.out.println("收到服务器发来的消息:"+msg);
}
/*
*建立连接时调用
*/
@Override
publicvoidchannelActive(ChannelHandlerContext context)throwsException {
super.channelActive(context);
}
}
相关推荐
- 一个基于.Net Core遵循Clean Architecture原则开源架构
-
今天给大家推荐一个遵循CleanArchitecture原则开源架构。项目简介这是基于Asp.netCore6开发的,遵循CleanArchitecture原则,可以高效、快速地构建基于Ra...
- AI写代码翻车无数次,我发现只要提前做好这3步,bug立减80%
-
写十万行全是bug之后终于找到方法了开发"提示词管理助手"新版本那会儿,我差点被bug整崩溃。刚开始两周,全靠AI改代码架构,结果十万行程序漏洞百出。本来以为AI说没问题就稳了,结果...
- OneCode低代码平台的事件驱动设计:架构解析与实践
-
引言:低代码平台的事件驱动范式在现代软件开发中,事件驱动架构(EDA)已成为构建灵活、松耦合系统的核心范式。OneCode低代码平台通过创新性的注解驱动设计,将事件驱动理念深度融入平台架构,实现了业务...
- 国内大厂AI插件评测:根据UI图生成Vue前端代码
-
在IDEA中安装大厂的AI插件,打开ruoyi增强项目:yudao-ui-admin-vue31.CodeBuddy插件登录腾讯的CodeBuddy后,大模型选择deepseek-v3,输入提示语:...
- AI+低代码技术揭秘(二):核心架构
-
本文档介绍了为VTJ低代码平台提供支持的基本架构组件,包括Engine编排层、Provider服务系统、数据模型和代码生成管道。有关UI组件库和widget系统的信息,请参阅UI...
- GitDiagram用AI把代码库变成可视化架构图
-
这是一个名为gitdiagram的开源工具,可将GitHub仓库实时转换为交互式架构图,帮助开发者快速理解代码结构。核心功能一键可视化:替换GitHubURL中的"hub...
- 30天自制操作系统:第六天:代码架构整理与中断处理
-
1.拆开bootpack.c文件。根据设计模式将对应的功能封装成独立的文件。2.初始化pic:pic(可编程中断控制器):在设计上,cpu单独只能处理一个中断。而pic是将8个中断信号集合成一个中断...
- AI写代码越帮越忙?2025年研究揭露惊人真相
-
近年来,AI工具如雨后春笋般涌现,许多人开始幻想程序员的未来就是“对着AI说几句话”,就能轻松写出完美的代码。然而,2025年的一项最新研究却颠覆了这一期待,揭示了一个令人意外的结果。研究邀请了16位...
- 一键理解开源项目:两个自动生成GitHub代码架构图与说明书工具
-
一、GitDiagram可以一键生成github代码仓库的架构图如果想要可视化github开源项目:https://github.com/luler/reflex_ai_fast,也可以直接把域名替换...
- 5分钟掌握 c# 网络通讯架构及代码示例
-
以下是C#网络通讯架构的核心要点及代码示例,按协议类型分类整理:一、TCP协议(可靠连接)1.同步通信//服务器端usingSystem.Net.Sockets;usingTcpListene...
- 从复杂到优雅:用建造者和责任链重塑代码架构
-
引用设计模式是软件开发中的重要工具,它为解决常见问题提供了标准化的解决方案,提高了代码的可维护性和可扩展性,提升了开发效率,促进了团队协作,提高了软件质量,并帮助开发者更好地适应需求变化。通过学习和应...
- 低代码开发当道,我还需要学习LangChain这些框架吗?| IT杂谈
-
专注LLM深度应用,关注我不迷路前两天有位兄弟问了个问题:当然我很能理解这位朋友的担忧:期望效率最大化,时间用在刀刃上,“不要重新发明轮子”嘛。铺天盖地的AI信息轰炸与概念炒作,很容易让人浮躁与迷茫。...
- 框架设计并不是简单粗暴地写代码,而是要先弄清逻辑
-
3.框架设计3.框架设计本节我们要开发一个UI框架,底层以白鹭引擎为例。框架设计的第一步并不是直接撸代码,而是先想清楚设计思想,抽象。一个一个的UI窗口是独立的吗?不是的,...
- 大佬用 Avalonia 框架开发的 C# 代码 IDE
-
AvalonStudioAvalonStudio是一个开源的跨平台的开发编辑器(IDE),AvalonStudio的目标是成为一个功能齐全,并且可以让开发者快速使用的IDE,提高开发的生产力。A...
- 轻量级框架Lagent 仅需20行代码即可构建自己的智能代理
-
站长之家(ChinaZ.com)8月30日消息:Lagent是一个专注于基于LLM模型的代理开发的轻量级框架。它的设计旨在简化和提高这种模型下代理的开发效率。LLM模型是一种强大的工具,可以...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- 框架图 (58)
- flask框架 (53)
- quartz框架 (51)
- abp框架 (47)
- springmvc框架 (49)
- 分布式事务框架 (65)
- scrapy框架 (56)
- shiro框架 (61)
- 定时任务框架 (56)
- java日志框架 (61)
- mfc框架 (52)
- abb框架断路器 (48)
- beego框架 (52)
- java框架spring (58)
- grpc框架 (65)
- tornado框架 (48)
- 前端框架bootstrap (54)
- orm框架有哪些 (51)
- 知识框架图 (52)
- ppt框架 (55)
- 框架图模板 (59)
- 内联框架 (52)
- cad怎么画框架 (58)
- ssm框架实现登录注册 (49)
- oracle字符串长度 (48)