- ByteBuf
- 类图
- ByteBuf 与 ByteBuffer
- 属性 / 方法
- ByteBuf相关辅助类
- ByteBufHolder
- ByteBufAllocator
- CompositeByteBuf
- ByteBufUtil
1. ByteBuf
1.1 ByteBuf类图
1.2 ByteBuf 与 ByteBuffer的区别
- ByteBuffer中只有一个index,ByteBuf中有readIndex和writeIndex
- 由于有两个index,ByteBuf不需要flip()
- ByteBuffer的缓冲区空间是固定的,ByteBuf可以动态扩展。使用writeByte()时,容量不足会自动扩展
1.3 代码分析
- 属性
int readerIndex;
int writerIndex;读写的index private int markedReaderIndex;
private int markedWriterIndex;暂存的tempIndex,配合reset()和mark()方法使用 private int maxCapacity; 缓冲区最大容量 static final ResourceLeakDetector<ByteBuf> leakDetector; 用于检测对象是否泄露 - 方法
read相关 读取成功后,对应readIndex += length write相关 1. 写入成功后,对应writeIndex += length
2. 动态扩容机制:maxCapacity <= 4M时,maxCapacity *= 2倍增
maxCapacity > 4M时,maxCapacity += 4M
目的是防止内存膨胀和浪费
每次扩容时,建新的缓冲区,再复制过去
操作readIndex和writeIndex 包括读写索引的方法,mark()和reset() 重用缓冲区 discardReadBytes和discardSomeReadBytes方法
把已读取过(<readIndex)的Byte全部丢弃
将readIndex移动到0的位置,同时writeIndex也对应偏移
2. 相关辅助类
2.1 ByteBufHolder
- 对不同的协议消息体进行包装和抽象(如HTTP协议的请求消息和应答消息)
2.2 ByteBufAllocator
- 字节缓冲分配器
2.3 CompositeByteBuf
2.4 ByteBufUtil
- 提供一系列静态方法用于操作ByteBuf对象
- 比较常用的方法有
- public static ByteBuf encodeString(ByteBufAllocator alloc, CharBuffer src, Charset charset):对src按照charset进行编码,并根据alloc生成新的ByteBuf
- static String decodeString(ByteBuf src, int readerIndex, int len, Charset charset):对src根据charset进行解码,获取解码后的字符串
- hexDump(ByteBuf):将参数ByteBuf的内容以十六进制字符串的形式打印出来