【netty】 ByteBuf的常用API总结

博客围绕Netty中ByteBuf展开,介绍了其创建方式,包括池化创建ByteBufAllocator、Unpooled非池化缓存及ByteBufUtil创建;还阐述了读、写操作,读操作分get和read,get不改变读索引,read会改变;此外,还涉及索引管理、查找、副本等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://blog.youkuaiyun.com/qq_26680031/article/details/79118878

一、创建

1、池化创建 ByteBufAllocator

获取ByteBufAllocator

Channel channel = ...;ByteBufAllocator allocator = channel.alloc(); //1....ChannelHandlerContext ctx = ...;ByteBufAllocator allocator2 = ctx.alloc(); //2

 

ByteBufAllocator中创建byteBuf的方法

名称

描述

buffer() buffer(int) buffer(int, int)

Return a ByteBuf with heap-based or direct data storage.

heapBuffer() heapBuffer(int) heapBuffer(int, int)

Return a ByteBuf with heap-based storage.

directBuffer() directBuffer(int) directBuffer(int, int)

Return a ByteBuf with direct storage.

compositeBuffer() compositeBuffer(int) heapCompositeBuffer() heapCompositeBuffer(int) directCompositeBuffer()directCompositeBuffer(int)

Return a CompositeByteBuf that can be expanded by adding heapbased or direct buffers.

ioBuffer()

Return a ByteBuf that will be used for I/O operations on a socket.

2、Unpooled (非池化)缓存

当未引用 ByteBufAllocator 时,上面的方法无法访问到 ByteBuf。对于这个用例 Netty 提供一个实用工具类称为 Unpooled,,它提供了静态辅助方法来创建非池化的 ByteBuf 实例。表5.9列出了最重要的方法

Table 5.9 Unpooled helper class

名称

描述

buffer() buffer(int) buffer(int, int)

Returns an unpooled ByteBuf with heap-based storage

directBuffer() directBuffer(int) directBuffer(int, int)

Returns an unpooled ByteBuf with direct storage

wrappedBuffer()

Returns a ByteBuf, which wraps the given data.

copiedBuffer()

Returns a ByteBuf, which copies the given data

在 非联网项目,该 Unpooled 类也使得它更容易使用的 ByteBuf API,获得一个高性能的可扩展缓冲 API,

3、ByteBufUtil创建 (ByteBufUtil中有很多操作buf的API)

 

二、读 get/read get不会改变读索引,read会改变读索引

getBoolean(int)

返回当前索引的 Boolean 值

getByte(int) getUnsignedByte(int)

返回当前索引的(无符号)字节

getMedium(int) getUnsignedMedium(int)

返回当前索引的 (无符号) 24-bit 中间值

getInt(int) getUnsignedInt(int)

返回当前索引的(无符号) 整型

getLong(int) getUnsignedLong(int)

返回当前索引的 (无符号) Long 型

getShort(int) getUnsignedShort(int)

返回当前索引的 (无符号) Short 型

getBytes(int, ...)

字节

 

方法名称

描述

readBoolean() 

 返回当前索引的Boolean值,读索引加一

readByte() 

readUnsignedByte() 

返回当前索引的(无符号)字节,读索引加一

readMedium() 

readUnsignedMedium() 

返回当前索引的 (无符号) 24-bit 中间值,读索引加3

readInt() 

readUnsignedInt()

 返回当前索引的(无符号) 整型,读索引加4

readLong() 

readUnsignedLong() 

 返回当前索引的 (无符号) Long 型,读索引加8

readShort() 

readUnsignedShort() 

返回当前索引的 (无符号) Short 型,读索引加2

readBytes(int,int, ...)

、放回当前位置到length

得一个字节数组,读索引加length

 

 

三、写操作 set/write

方法名称

描述

setBoolean(int, boolean)

在指定的索引位置设置 Boolean 值

setByte(int, int)

在指定的索引位置设置 byte 值

setMedium(int, int)

在指定的索引位置设置 24-bit 中间 值

setInt(int, int)

在指定的索引位置设置 int 值

setLong(int, long)

在指定的索引位置设置 long 值

setShort(int, int)

在指定的索引位置设置 short 值

 

方法名称

描述

writeBoolean(boolean)

在指定的索引位置设置 Boolean 值,写索引加一

writeByte(int)

在指定的索引位置设置 byte 值,写索引加一

writeMedium(int)

在指定的索引位置设置 24-bit 中间 值,写索引加3

writeInt(int)

在指定的索引位置设置 int 值,写索引加4

writeLong(long)

在指定的索引位置设置 long 值,写索引加8

writeShort(int)

在指定的索引位置设置 short 值,写索引加2

writeBytes(int,...)

 在当前索引写入一个Byte数组,写索引加数组长度

 

四、索引管理

markReaderIndex(),

 markWriterIndex()

标记读(写)索引

resetReaderIndex()

resetWriterIndex()

读(写)索引回到mark标记的索引值

readerIndex(int)

 writerIndex(int) 

将读(写)索引设置到指定位置

clear()

可以同时设置 readerIndex 和 writerIndex 为 0。这不会清除内存中的内容

 

五、查找

forEachByte(ByteBufProcessor.FIND_NUL)

查找byte,返回byte的索引

 

六、副本

duplicate()

slice()

slice(int, int)

readOnly(),

order(ByteOrder) 

所有这些都返回一个新的 ByteBuf 实例包括它自己的 reader, writer 和标记索引。然而,内部数据存储共享就像在一个 NIO 的 ByteBuffer

 copy()

 copy(int, int)

返回的 ByteBuf 有数据的独立副本。

 

七、其他

方法名称

描述

isReadable()

返回是否有字节可读

isWritable()

返回是否可以写

readableBytes()

返回可以读的字节长度

writablesBytes()

返回可以写的字节场地

capacity()

返回byteBuf的容量

maxCapacity()

返回byteBuf可以有的最大容量

hasArray()

如果byteBuf可以直接返回一个数组就返回true

(heap buf才会为true)

array()

hasArray返回true,该方法就会返回一个数组

### Netty 常用 API 列表及其使用方法 #### 1. **Channel** `Channel` 是 Netty 中的一个核心接口,表示一个网络连接。通过 `Channel` 可以读取和写入数据[^1]。 - **主要功能**: 提供对底层 I/O 操作的抽象。 - **常见实现类**: - `SocketChannel`: 表示 TCP 客户端连接。 - `ServerSocketChannel`: 表示 TCP 服务端监听器。 ```java // 获取 Channel 配置选项 channel.config().setOption(ChannelOption.SO_BACKLOG, 128); ``` --- #### 2. **ChannelHandler** `ChannelHandler` 是用于处理各种事件(如读、写、异常等)的组件。它是 Netty 处理业务逻辑的主要入口[^2]。 - **分类**: - `ChannelInboundHandler`: 负责处理入站事件。 - `ChannelOutboundHandler`: 负责处理出站事件。 - **常用子类**: - `SimpleChannelInboundHandler<T>`: 自动释放资源并简化了消息接收流程。 - `ChannelInitializer<Channel>`: 初始化管道时添加其他处理器。 ```java public class MyHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("Received message: " + msg); } } ``` --- #### 3. **ChannelPipeline** `ChannelPipeline` 是一组按顺序排列的 `ChannelHandler` 实例集合。它负责管理这些处理器之间的交互[^4]。 - **作用**: 将不同的操作分配给特定的 `ChannelHandler` 来完成。 - **常用方法**: - `addLast(ChannelHandler handler)`:向管道末尾添加一个新的处理器。 - `remove(ChannelHandler handler)`:移除指定的处理器。 ```java pipeline.addLast(new LoggingHandler()); pipeline.addLast(new MyHandler()); ``` --- #### 4. **ChannelHandlerContext** `ChannelHandlerContext` 表示某个 `ChannelHandler` 在 `ChannelPipeline` 中的状态和上下文信息。 - **用途**: 提供访问当前 `ChannelHandler` 所属的 `Channel` 和 `ChannelPipeline` 的能力。 - **常用方法**: - `write(Object msg)`:将消息发送到下游。 - `fireChannelRead(Object msg)`:触发上游的读事件。 ```java ctx.writeAndFlush(msg); // 向下一个处理器传递消息 ``` --- #### 5. **EventLoopGroup** `EventLoopGroup` 是一组线程池,专门用来执行 I/O 操作的任务调度。 - **典型实现**: - `NioEventLoopGroup`: 基于 NIO 的多路复用机制。 - **配置实例**: ```java EventLoopGroup bossGroup = new NioEventLoopGroup(); // 接受新连接 EventLoopGroup workerGroup = new NioEventLoopGroup(); // 处理已建立的连接 try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new MyInitializer()); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } ``` --- #### 6. **ServerBootstrap / Bootstrap** 这两个类分别用于启动服务器和服务端/客户端程序。 - **区别**: - `ServerBootstrap`: 专为服务器设计。 - `Bootstrap`: 主要针对客户端场景。 - **初始化代码片段**: ```java ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(group) .channel(NioServerSocketChannel.class) .childHandler(new InitializerClass()); ``` --- #### 7. **Unpooled 类** 当不需要频繁创建缓冲区时,可以直接使用静态工具类 `Unpooled` 创建 ByteBuf 对象。 ```java ByteBuf buffer = Unpooled.buffer(1024); // 分配大小为 1024 字节的缓冲区 buffer.writeBytes("Hello".getBytes()); // 写入字节数组 ``` --- #### 8. **ChannelFuture** `ChannelFuture` 表示异步操作的结果。由于 Netty 是全异步框架,因此所有的 I/O 操作都会返回一个 Future 对象[^3]。 - **特点**: 支持回调函数注册。 - **示例**: ```java ChannelFuture future = channel.closeFuture(); // 注册关闭事件 future.addListener(f -> { if (f.isSuccess()) { System.out.println("Connection closed successfully."); } else { f.cause().printStackTrace(); } }); ``` --- #### 总结 上述列举的是 Netty 中最常使用的几个核心 API。它们共同构成了 Netty 的基础架构,开发者可以通过组合这些模块快速构建高性能的网络应用。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值