Unpooled 是一个工具类,类如其名,提供了非池化的 ByteBuf 创建、组合、复制等操作

    这里仅介绍其跟【零拷贝】相关的 wrappedBuffer 方法,可以用来包装 ByteBuf

    1. ByteBuf buf1 = ByteBufAllocator.DEFAULT.buffer(5);
    2. buf1.writeBytes(new byte[]{1, 2, 3, 4, 5});
    3. ByteBuf buf2 = ByteBufAllocator.DEFAULT.buffer(5);
    4. buf2.writeBytes(new byte[]{6, 7, 8, 9, 10});
    5. // 当包装 ByteBuf 个数超过一个时, 底层使用了 CompositeByteBuf
    6. ByteBuf buf3 = Unpooled.wrappedBuffer(buf1, buf2);
    7. System.out.println(ByteBufUtil.prettyHexDump(buf3));

    输出

    1. +-------------------------------------------------+
    2. | 0 1 2 3 4 5 6 7 8 9 a b c d e f |
    3. +--------+-------------------------------------------------+----------------+
    4. |00000000| 01 02 03 04 05 06 07 08 09 0a |.......... |
    5. +--------+-------------------------------------------------+----------------+

    也可以用来包装普通字节数组,底层也不会有拷贝操作

    1. ByteBuf buf4 = Unpooled.wrappedBuffer(new byte[]{1, 2, 3}, new byte[]{4, 5, 6});
    2. System.out.println(buf4.getClass());
    3. System.out.println(ByteBufUtil.prettyHexDump(buf4));

    输出

    1. class io.netty.buffer.CompositeByteBuf
    2. +-------------------------------------------------+
    3. | 0 1 2 3 4 5 6 7 8 9 a b c d e f |
    4. +--------+-------------------------------------------------+----------------+
    5. |00000000| 01 02 03 04 05 06 |...... |
    6. +--------+-------------------------------------------------+----------------+