跳转至

Netty Buffer 概念

一、NIO Buffer

Java NIO 的 Buffer:

ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put((byte) 1);
buf.flip();
buf.get();

四个属性

  • capacity:容量。
  • limit:读写上限。
  • position:当前位置。
  • mark:标记。

二、Netty ByteBuf

Netty 重新设计的 Buffer:

ByteBuf buf = Unpooled.buffer(1024);
buf.writeBytes(...);
buf.readBytes(...);

三、对比 NIO Buffer

NIO Buffer Netty ByteBuf
读写切换 flip() 不用
指针 一个 position readerIndex + writerIndex
动态扩展 不支持 支持
池化 不支持 支持

四、池化 ByteBuf

PooledByteBufAllocator: - 复用内存。 - 减少 GC。 - 线程安全。

五、零拷贝

Netty 的 CompositeByteBuf 把多个 Buffer 合成一个,不复制。

六、为什么用 ByteBuf

  • 不用 flip,API 友好。
  • 池化性能高。
  • 零拷贝。

面试一句话

Netty Buffer = 读写指针分离 + 池化 + 零拷贝。