什么是ByteBuf?

ByteBuf在Netty中充当着非常重要的角色;它是在数据传输中负责装载字节数据的一个容器;其内部结构和数组类似,初始化默认长度为256,默认最大长度为Integer.MAX_VALUE。

ByteBuf数据结构

* <pre>  *      +-------------------+------------------+------------------+  *      | discardable bytes |  readable bytes  |  writable bytes  |  *      |                   |     (CONTENT)    |                  |  *      +-------------------+------------------+------------------+  *      |                   |                  |                  |  *      0      <=      readerIndex   <=   writerIndex    <=    capacity  * </pre>

ByteBuf字节缓冲区主要由discardablereadablewritable三种类型的字节组成的;

ByteBuf字节缓冲区可以操控readerIndexwriterIndex二个下标;这两个下标都是单独维护

名词 解释 方法
discardable bytes 丢弃的字节;ByteBuf中已经读取的字节 discardReadBytes();
readable bytes 剩余的可读的字节  
writable bytes 已经写入的字节  
readerIndex 字节读指针(数组下标) readerIndex()
writerIndex 字节写指针(数组下标) writerIndex()

ByteBuf中主要的类-UML图

avatar

ByteBuf怎么创建的?

ByteBuf是通过Unpooled来进行创建;默认长度为256,可自定义指定长度,最大长度为Integer.MAX_VALUE;

ByteBuf创建的类型有哪几种?

1. 基于内存管理分类

类型 解释 对应的字节缓冲区类
Pooled 池化;
简单的理解就是pooled拥有一个pool池空间(poolArea),
凡是创建过的字节缓冲区都会被缓存进去,
有新的连接需要字节缓冲区会先从缓存中get,
取不到则在进行创建;
1.PooledDirectByteBuf
2.PooledHeapByteBuf
3.PooledUnsafeDirectByteBuf
4.PooledUnsafeHeapByteBuf
Unpooled 非池化;
每次都会创建一个字节缓冲区
1.UnpooledDirectByteBuf
2.UnpooledHeapByteBuf
3.UnpooledUnsafeDirectByteBuf
4.UnpooledUnsafeHeapByteBuf