【问题标题】:Efficient way to convert io.netty.buffer.ByteBuf to java.nio.ByteBuffer将 io.netty.buffer.ByteBuf 转换为 java.nio.ByteBuffer 的有效方法
【发布时间】:2013-10-18 16:45:16
【问题描述】:

我遇到了这个查询:Create a ByteBuf in Netty 4.0 关于从 byte[] 到 ByteBuf 以及从 ByteBuffer 到 ByteBuf 的转换。我很想知道以另一种方式进行的转换:

io.netty.buffer.ByteBuf 到 java.nio.ByteBuffer

以及如何有效地做到这一点,最少/不复制?我做了一些阅读,经过反复试验,我发现这种转换方式效率低下(有两份):

// io.netty.handler.codec.http.FullHttpRequest fullHttpRequest;
ByteBuf conByteBuf = fullHttpRequest.content ();                  
int numReadBytes = conByteBuf.readableBytes ();
conBytes = new byte[numReadBytes];
conByteBuf .readBytes (conBytes);                                // First Copy
ByteBuffer conByteBuffer = ByteBuffer.allocate (conBytes.length);
conByteBuffer.put (conByteBuf);                                  // Second Copy

我的问题是,我们能否避免一个或两个副本,让 ByteBuffer 的内部缓冲区使用 ByteBuf 的内部缓冲区。

谢谢!

【问题讨论】:

    标签: java netty bytebuffer


    【解决方案1】:

    您应该可以使用ByteBuf.nioBuffers()。它将以 ByteBuffer 对象数组的形式返回 ByteBuf 的视图。

    在大多数情况下,这个数组只有一个元素,但在 ByteBuf 的一些更复杂的实现中,可能有多个底层 ByteBuffer 对象,ByteBuf.nioBuffers() 可以按原样返回它们,而不是像合并它们那样合并它们致电ByteBuf.nioBuffer()

    您可以使用 ByteBuf.nioBufferCount() 提前知道数组长度是多少

    【讨论】:

    • 当它被一个字节[]支持时,这不会解决
    • @Dev,当您使用ByteBuf.nioBuffers()ByteBuf.nioBuffer() 将 ByteBuf 的视图返回为 ByteBuffer 对象数组或单个 ByteBuffer 对象时,如果您要释放 ByteBuf 会发生什么?由于 ByteBuf 和 ByteBuffer 共享底层数据,因此出现这种情况时,创建的 ByteBuffer 对象似乎会出现问题。
    • 所以ByteBuf.nioBuffer() 自动将它们合并为一个?我可以直接调用它而不是遍历 nioBuffers() 中的数组?
    【解决方案2】:

    你至少可以使用ByteBuffer.wrap()来避免第二次复制。

    【讨论】:

    • 我们还能避免第一次复制吗?
    • Dev 下面的回复似乎有助于消除这种情况。
    【解决方案3】:

    效率不是特别高,但可以解决问题:

    public static ByteBuffer toNioBuffer(ByteBuf buffer) {
        if (buffer.isDirect()) {
            return buffer.nioBuffer();
        }
        final byte[] bytes = new byte[buffer.readableBytes()];
        buffer.getBytes(buffer.readerIndex(), bytes);
        return ByteBuffer.wrap(bytes);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 2021-07-15
      • 1970-01-01
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多