Netty--ByteBuf
目錄
?
NIO ByteBuffer局限性
ByteBuf功能
基本功能
讀寫功能
擴(kuò)容與收縮
查找
Derived buffers
ByteBuffer互轉(zhuǎn)換
ByteBuf源碼
ByteBuf結(jié)構(gòu)
繼承關(guān)系
分類
AbstractByteBuf
AbstractReferenceCountedByteBuf
UnpooledHeapByteBuf
PooledByteBuf
PooledDirectByteBuf
輔助類
ByteBufHolder
ByteBufAllocator
CompositeByteBuf
ByteBufUtil
NIO ByteBuffer局限性
- ByteBuffer長度固定,不能動態(tài)擴(kuò)展和收縮。
- ByteBuffer只有一個position標(biāo)識位置,讀寫需要flip()和rewind()來翻轉(zhuǎn),較難控制。
- API功能有限。
ByteBuf功能
基本功能
- 7種基礎(chǔ)類型,byte數(shù)組,ByteBuffer(ByteBuf)等的讀寫
- copy,slice等
- 設(shè)置字節(jié)順序
- 構(gòu)造實(shí)例
- 操作位置指針
讀寫功能
ByteBuf通過readIndex和writeIndex協(xié)助緩沖區(qū)讀寫操作。0 <= readIndex <= writeIndex <= capacity 。
ByteBuf讀寫方法分為:
- getXXX(int index):返回指定索引位置的指定類型的值。不改變readIndex和writeIndex。
- readXXX():讀取指定類型的值,會修改readIndex的值,根據(jù)指定類型增加readIndex。
- setXXX(int index,XXX value):設(shè)置指定索引位置的值,不改變readIndex和writeIndex。
- writeXXX(XXX value):寫入指定類型的值。會修改writeIndex的值,根據(jù)指定類型增加writeIndex。
在每次put操作時,都需要檢查剩余空間,如果空間不足,則會創(chuàng)建一個新的ByteBuf
擴(kuò)容與收縮
- discardReadBytes():收回丟棄空間,內(nèi)部copy,移動readIdnex,writeIndex。
- clear():清空緩沖區(qū),不填充任何信息,僅修改readIndex,writeIndex為0
- markReaderIndex()和markWriterIndex():
- resetReaderIndex()和resetWriterIndex():
查找
- indexOf(...)
- bytesBefore(...)
- forEachByte(...)
Derived buffers
- duplicate():與源Buffer共享緩沖區(qū)。
- copy(...):不與源Buffer共享緩沖區(qū)。
- slice(...):與源Buffer共享緩沖區(qū)。
ByteBuffer互轉(zhuǎn)換
- nioBuffer(...)
- nioBuffers(...)
ByteBuf源碼
ByteBuf結(jié)構(gòu)
繼承關(guān)系
分類
內(nèi)存分配角度:
- 堆內(nèi)存(HeapByteBuf)
內(nèi)存分配和回收速度快,可以被JVM回收。由于需要做一次內(nèi)核Copy,性能低。
- 直接內(nèi)存(DirectByteBuf)
堆外內(nèi)存,內(nèi)存分配和回收速度快。不需要做一次內(nèi)核Copy,性能高。
最佳實(shí)踐:I/O通信讀寫緩沖區(qū)用DirectByteBuf;業(yè)務(wù)消息編解碼使用HeapByteBuf。
內(nèi)存回收角度
- 基于池ByteBuf:可以重用ByteBuf。
- 普通ByteBuf
AbstractByteBuf
ResourceLeakDetector leakDetector;
用于檢測對象是否泄漏。
AbstractReferenceCountedByteBuf
ReferenceCountUpdater
UnpooledHeapByteBuf
??? private final ByteBufAllocator alloc;
 ??? byte[] array;
 ??? private ByteBuffer tmpNioBuf;
PooledByteBuf<T>
??? private final Recycler.Handle<PooledByteBuf<T>> recyclerHandle;
??? protected PoolChunk<T> chunk;
 ??? protected long handle;
 ??? protected T memory;
 ??? protected int offset;
 ??? protected int length;
 ??? int maxLength;
 ??? PoolThreadCache cache;
 ??? ByteBuffer tmpNioBuf;
 ??? private ByteBufAllocator allocator;
PooledDirectByteBuf
輔助類
ByteBufHolder
ByteBufHolder是ByteBuf的容器。
ByteBufAllocator
字節(jié)緩沖區(qū)分配器。
PooledByteBufAllocator
UnpooledByteBufAllocator
CompositeByteBuf
多個ByteBuf實(shí)例組裝視圖。
ByteBufUtil
工具類
?
?
?
總結(jié)
以上是生活随笔為你收集整理的Netty--ByteBuf的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Netty--Reactor模式
- 下一篇: Netty--Future和Promis
