将io.netty.buffer.ByteBuf转换为java.nio.ByteBuffer的有效方法 [英] Efficient way to convert io.netty.buffer.ByteBuf to java.nio.ByteBuffer

查看:1039
本文介绍了将io.netty.buffer.ByteBuf转换为java.nio.ByteBuffer的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下查询:在Netty中创建ByteBuf 4.0 关于从byte []到ByteBuf的转换以及从ByteBuffer到ByteBuf的转换.我很好奇以另一种方式了解转换:

I came across this query: Create a ByteBuf in Netty 4.0 about conversion from byte[] to ByteBuf and ByteBuffer to ByteBuf. I was curious to know about the conversion the other way:

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

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

,以及如何有效地进行复制(最少/无复制)?我做了一些阅读,并且经过反复试验,发现这种转换效率低下的方式(带有两个副本):

and how to do it efficiently, with minimal/no copying? I did some reading and with some trial and error I found this inefficient way of converting it (with two copies):

// 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的内部缓冲区吗?

My question is, can we avoid one or both the copies and make the internal buffer of ByteBuffer to use the internal buffer of ByteBuf.

谢谢!

推荐答案

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

You can at least use ByteBuffer.wrap() to avoid the second copying.

这篇关于将io.netty.buffer.ByteBuf转换为java.nio.ByteBuffer的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆