ByteBuf 是对字节数据的封装
优点小结:
- 支持池化。可以重用池中的ByteBuf实例,更节约内存,减少内存溢出可能
- 它可以被用户自定义的缓冲区类型扩展;
- 通过内置的复合缓冲区类型实现了透明的零拷贝;
- 自动扩容,容量可以按需增长(类似于 JDK 的 StringBuilder);
- 读写指针分离,在读和写这两种模式之间切换不需要调用 ByteBuffer 的 flip()方法;
- 支持方法的链式调用;
- 支持引用计数;
ByteBuf 创建
- 默认容量256个字节,可指定初始容量
- 可动态扩容,nio的ByteBuffer不可扩容,超过就报错
ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();@Slf4jpublic class TestByteBuf { public static void main(String[] args) { //1.默认容量是265,可指定容量 //2.可动态扩容,nio的ByteBuffer不可扩容,超过就报错 ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(10); log(buf); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 12; i++) { sb.append("a"); } buf.writeBytes(sb.toString().getBytes()); log(buf);
} private static void log(ByteBuf buffer) { int length = buffer.readableBytes(); int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4; StringBuilder buf = new StringBuilder(rows * 80 * 2) .append("read index:").append(buffer.readerIndex()) .append(" write index:").append(buffer.writerIndex()) .append(" capacity:").append(buffer.capacity()) .append(NEWLINE); appendPrettyHexDump(buf, buffer); System.out.println(buf.toString()); }}read index:0 write index:0 capacity:10
read index:0 write index:12 capacity:16 +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f |+--------+-------------------------------------------------+----------------+|00000000| 61 61 61 61 61 61 61 61 61 61 61 61 |aaaaaaaaaaaa |+--------+-------------------------------------------------+----------------+直接内存 vs 堆内存
可以使用下面的代码来创建池化基于堆的 ByteBuf
ByteBuf buffer = ByteBufAllocator.DEFAULT.heapBuffer(10);也可以使用下面的代码来创建池化基于直接内存的 ByteBuf
ByteBuf buffer = ByteBufAllocator.DEFAULT.directBuffer(10);- 直接内存创建和销毁的代价昂贵,但读写性能高(少一次内存复制),适合配合池化功能一起用
- 直接内存对 GC 压力小,因为这部分内存不受 JVM 垃圾回收的管理,但也要注意及时主动释放
堆内存:分配效率高、读写效率低(会受到GC的影响);直接内存:分配效率低,读写效率高 Netty默认使用直接内存作为ByteBuf的内存
对于一些IO通信线程中读写缓冲时建议使用DirectByteBuffer,因为这涉及到大量的IO数据读写。对于后端的业务消息的编解码模块使用HeapByteBuffer。
池化 vs 非池化
池化的最大意义在于可以重用 ByteBuf,优点有
- 没有池化,则每次都得创建新的 ByteBuf 实例,这个操作对直接内存代价昂贵,就算是堆内存,也会增加 GC 压力
- 有了池化,则可以重用池中 ByteBuf 实例,并且采用了与 jemalloc 类似的内存分配算法提升分配效率
- 高并发时,池化功能更节约内存,减少内存溢出的可能
池化功能是否开启,可以通过下面的系统环境变量来设置
类名里带有Pooled的ByteBuf就是池化的
-Dio.netty.allocator.type={unpooled|pooled}- 4.1 之前,池化功能还不成熟,默认是非池化实现
- 4.1 以后,非 Android 平台默认启用池化实现,Android 平台启用非池化实现
对于一些创建比较慢的资源,我们可以利用池化思想,预先创建好。例如数据库连接池
ByteBuf 组成
ByteBuf提供了两个指针,一个读,一个写,相比于nio的ByteBuffer,在读和写模式之间切换不需要flip()方法
clear操作只是将读写指针设为0,而不会清空内容(不同于ByteBuffer是将limit设为capacity)
+-------------------+------------------+------------------+ | discardable bytes | readable bytes | writable bytes | | | (CONTENT) | | +-------------------+------------------+------------------+ | | | | 0 <= readerIndex <= writerIndex <= capacityByteBuf 写入
规律,write前缀的方法,如果有LE代表小端写入。
| 方法签名 | 含义 | 备注 |
|---|---|---|
| writeBoolean(boolean value) | 写入boolean值 | 用一字节01 |
| writeByte | 写入byte值 | |
| writeInt(int value) | 写入int值 | Big Endian ,即0x250, 写入后 00 00 02 50 |
| writeIntLE(int value) | 写入int值 | Little Endian,即0x250,写入后 50 02 00 00 |
| writeXxx(Xxx value) | 写入xx值 | |
| writeXxxLE(Xxx value) | Little Endian | |
| writeBytes(ByteBuffer src) | 写入nio的ByteBuffer | |
| int writeCharSequence(CharSequence sequence,Charset charset) | 写入字符串 |
这里的Big Endian和Little Endian是什么意思?(网络编程中常用的名词) Big Endian:大端写入,从高位字节写入;Little Endian:小端写入,从低位字节写入。 注意
- 这些方法的未指明返回值的, 其返回值都是ByteBuf,意味着可以链式调用
- 网络传输,默认习惯是Big Endian
还有一类方法是 set 开头的一系列方法,也可以写入数据,但不会改变写指针位置
ByteBuf 扩容
扩容规则:
- 如果写入后数据大小未超过
512,则选择下一个 16 的整数倍,例如写入后大小为 12 ,则扩容后 capacity 是 16 - 如果写入后数据大小超过 512,会按特定算法或 2 的幂次进行平滑扩容,选择下一个 ,例如写入后大小为 513,则扩容后 capacity 是 ( 已经不够了)
- 扩容不能超过 max capacity 会报错(max capacity =
Integer.MAX_VALUE-1)
ByteBuf 读取
readByte(),每次读取一个字节
ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(10); //设定初始容量为10buf.writeBytes(new byte[]{1,2,3,4});buf.writeInt(5);buf.writeInt(6); //扩容System.out.println(buffer.readByte());System.out.println(buffer.readByte());System.out.println(buffer.readByte());System.out.println(buffer.readByte());log(buffer);读取过的部分属于废弃部分,无法再读
1234read index:4 write index:12 capacity:16 +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f |+--------+-------------------------------------------------+----------------+|00000000| 00 00 00 05 00 00 00 06 |........ |+--------+-------------------------------------------------+----------------+如何重复读取?
- 先mark然后reset
read前先标记重制后的位置:
markReaderIndex()
readInt(); read后重制到标记的位置:resetReaderIndex() - 使用getXxx()方法,不会改变readIndex的位置
ByteBuf 内存回收——引用计数
由于 Netty 中有堆外内存的 ByteBuf 实现,堆外内存最好是手动来释放,而不是等 GC 垃圾回收。
- UnpooledHeapByteBuf 使用的是 JVM 内存,只需等 GC 回收内存即可
- UnpooledDirectByteBuf 使用的就是直接内存了,需要特殊的方法来回收内存
- PooledByteBuf 和它的子类使用了池化机制,需要更复杂的规则来回收内存
回收内存的源码实现,请关注
AbstractReferenceCountedByteBuf下面方法的不同实现
protected abstract void deallocate()
Netty 这里采用了引用计数法来控制回收内存,每个 ByteBuf 都实现了 ReferenceCounted 接口
- 每个 ByteBuf 对象的初始计数为 1
- 调用 release 方法计数减 1,如果计数为 0,ByteBuf 内存被回收
- 调用 retain 方法计数加 1,表示调用者没用完之前,其它 handler 即使调用了 release 也不会造成回收
- 当计数为 0 时,底层内存会被回收,这时即使 ByteBuf 对象还在,其各个方法均无法正常使用
A reference-counted object that requires explicit deallocation. When a new
ReferenceCountedis instantiated, it starts with the reference count of1.retain()increases the reference count, andrelease()decreases the reference count. If the reference count is decreased to0, the object will be deallocated explicitly, and accessing the deallocated object will usually result in an access violation. If an object that implementsReferenceCountedis a container of other objects that implementReferenceCounted, the contained objects will also be released viarelease()when the container’s reference count becomes0.
谁负责release
当一个ByteBuf需要在pipeline中传递时,应该由最后一个使用(不需要向后传递了)的handler进行内存释放。 例如,如果已经将ByteBuf转为我们需要的数据类型对象后,即可在finally中释放。
-
起点,对于 NIO 实现来讲,在 io.netty.channel.nio.AbstractNioByteChannel.NioByteUnsafe#read 方法中首次创建 ByteBuf 放入 pipeline(line 163 pipeline.fireChannelRead(byteBuf))
-
入站 ByteBuf 处理原则
-
对原始 ByteBuf 不做处理,调用 ctx.fireChannelRead(msg) 向后传递,这时无须 release
-
将原始 ByteBuf 转换为其它类型的 Java 对象,这时 ByteBuf 就没用了,必须 release
-
如果不调用 ctx.fireChannelRead(msg) 向后传递,那么也必须 release
-
注意各种异常,如果 ByteBuf 没有成功传递到下一个 ChannelHandler,必须 release
-
假设消息一直向后传,那么
TailContext会负责释放未处理消息(原始的 ByteBuf)// 如果没有入站处理器,或者ByteBuf一直传到了tail的话,就会由tail进行释放// io.netty.channel.DefaultChannelPipeline#onUnhandledInboundMessage(java.lang.Object)protected void onUnhandledInboundMessage(Object msg) {try {logger.debug("Discarded inbound message {} that reached at the tail of the pipeline. " +"Please check your pipeline configuration.", msg);} finally {ReferenceCountUtil.release(msg);}}⬇️// io.netty.util.ReferenceCountUtil#release(java.lang.Object)public static boolean release(Object msg) {// 如果是实现了ReferenceCounted接口的if (msg instanceof ReferenceCounted) {return ((ReferenceCounted) msg).release();}return false;}
-
-
出站 ByteBuf 处理原则
-
出站消息最终都会转为 ByteBuf 输出,一直向前传,由
HeadContextflush 后 release 判断了如果outboundBuffer为null的话,说明channel已经关闭了,释放Bytebuf 这里贴了issue,解释如下:Motivation: At the moment we do a Channel.isActive() check in every AbstractChannel.AbstractUnsafe.write(…) call which gives quite some overhead as shown in the profiler when you write fast enough. We can eliminate the check and do something more smart here.
Modifications: Remove the isActive() check and just check if the ChannelOutboundBuffer was set to null before, which means the Channel was closed. The rest will be handled in flush0() anyway.
@Overridepublic final void write(Object msg, ChannelPromise promise) {assertEventLoop();ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;if (outboundBuffer == null) {// If the outboundBuffer is null we know the channel was closed and so// need to fail the future right away. If it is not null the handling of the rest// will be done in flush0()// See https://github.com/netty/netty/issues/2362safeSetFailure(promise, newClosedChannelException(initialCloseCause));// release message now to prevent resource-leakReferenceCountUtil.release(msg);return;}}
-
-
异常处理原则
- 有时候不清楚 ByteBuf 被引用了多少次,但又必须彻底释放,可以循环调用 release 直到返回 true
Bytebuf — “零拷贝”
这里说的零拷贝与nio时说的零拷贝不同,那里指的是操作系统层面的,减少一次内存的复制。从文件io到socket缓冲区。而这里指的是Bytebuf的一些API层面的。
slice
对原始 ByteBuf 进行切片成多个 ByteBuf,切片后的 ByteBuf 并没有发生内存复制,还是使用原始 ByteBuf 的内存,切片后的 ByteBuf 维护独立的 read,write 指针 需要注意的是,slice()返回的ByteBuf不可再往里面写入。 并且在使用前调用retain()方法,使得引用+1,否则如果原始的ByteBuf调用release()之后再使用会报错。
ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(10);byteBuf.writeBytes(new byte[]{'a','b','c','d','e','f','g','h','i','j'});ByteBuf buf1 = byteBuf.slice(0, 5);ByteBuf buf2 = byteBuf.slice(5, 5);byteBuf.release();log(buf1); //报错io.netty.util.IllegalReferenceCountException: refCnt: 0
//========================正确的使用方法====================ByteBuf buf1 = byteBuf.slice(0,5);buf1.retain();byteBuf.release();
buf1.readByte();buf1.release(); //使用完后进行引用-1duplicate
截取了原始 ByteBuf 所有内容,并且没有 max capacity 的限制,也是与原始 ByteBuf 使用同一块底层内存,只是读写指针是独立的
copy
数据深拷贝,重新分配内存复制。无论读写都与ByteBuf无关
composite
可以将多个 ByteBuf 合并为一个逻辑上的 ByteBuf,避免拷贝
ByteBuf buf1 = ByteBufAllocator.DEFAULT.buffer();buf1.writeBytes(new byte[]{1,2,3,4,5});ByteBuf buf2 = ByteBufAllocator.DEFAULT.buffer();buf1.writeBytes(new byte[]{6,7,8,9,10});
//方法一:数据进行了多次拷贝ByteBuf buf3 = ByteBufAllocator.DEFAULT .buffer(buf1.readableBytes()+buf2.readableBytes());buf3.writeBytes(buf1).writeBytes(buf2);
//方法二:CompositeByteBuf compositeByteBuf = ByteBufAllocator.DEFAULT.compositeBuffer(); //不会自动增长写指针// compositeByteBuf.addComponents(buf1,buf2);//true 表示增加新的 ByteBuf 自动递增 write index, 否则 write index 会始终为 0compositeByteBuf.addComponents(true,buf1,buf2);结果是一样的
compositeByteBuf 是一个组合的 ByteBuf,它内部维护了一个 Component 数组,每个 Component 管理一个 ByteBuf,记录了这个 ByteBuf 相对于整体偏移量等信息,代表着整体中某一段的数据。
- 优点,对外是一个虚拟视图,组合这些 ByteBuf 不会产生内存复制
- 缺点,复杂了很多,多次操作会带来性能的损耗
for (ci = cIndex; arrOffset < len; arrOffset++, ci++) { ByteBuf b = buffers[arrOffset]; if (b == null) { break; } Component c = newComponent(ensureAccessible(b), nextOffset); components[ci] = c; nextOffset = c.endOffset;}Unpooled
Unpooled 是一个工具类,类如其名,提供了非池化的 ByteBuf 创建、组合、复制等操作
这里仅介绍其跟【零拷贝】相关的 wrappedBuffer 方法,可以用来包装 ByteBuf
ByteBuf buf1 = ByteBufAllocator.DEFAULT.buffer(5);buf1.writeBytes(new byte[]{1, 2, 3, 4, 5});ByteBuf buf2 = ByteBufAllocator.DEFAULT.buffer(5);buf2.writeBytes(new byte[]{6, 7, 8, 9, 10});
// 当包装 ByteBuf 个数超过一个时, 底层使用了 CompositeByteBufByteBuf buf3 = Unpooled.wrappedBuffer(buf1, buf2);System.out.println(ByteBufUtil.prettyHexDump(buf3));输出
+-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f |+--------+-------------------------------------------------+----------------+|00000000| 01 02 03 04 05 06 07 08 09 0a |.......... |+--------+-------------------------------------------------+----------------+也可以用来包装普通字节数组,底层也不会有拷贝操作
ByteBuf buf4 = Unpooled.wrappedBuffer(new byte[]{1, 2, 3}, new byte[]{4, 5, 6});System.out.println(buf4.getClass());System.out.println(ByteBufUtil.prettyHexDump(buf4));输出
class io.netty.buffer.CompositeByteBuf +-------------------------------------------------+ | 0 1 2 3 4 5 6 7 8 9 a b c d e f |+--------+-------------------------------------------------+----------------+|00000000| 01 02 03 04 05 06 |...... |+--------+-------------------------------------------------+----------------+

