
我的新课《C2C 电商系统微服务架构120天实战训练营》在公众号儒猿技术窝上线了,感兴趣的同学,可以长按扫描下方二维码了解课程详情:
课程大纲请参见文末

文章来自投稿:码农神说

tranferTo在上一篇推文有较详细的讲解,此处不再累述。
You can define your buffer type if necessary.根据需要可以定制自己的buffer类型。 Transparent zero copy is achieved by built-in composite buffer type.通过内建的组合类型可以实现透明的零拷贝。 A dynamic buffer type is provided out-of-the-box, whose capacity is expanded on demand, just like `StringBuffer`.它是一个开箱即用可根据需求动态扩展的buffer,就像`StringBuffer`。 There's no need to call the `flip()` method anymore.不再需要调用`flip()` 方法。 It is often faster than `ByteBuffer`.通常比`ByteBuffer`更快速。


allocating many short-lived direct NIO buffers often causes an OutOfMemoryError.


byte[] tmp=new byte[]{1,2};//Java NIO//传统方式(拷贝)ByteBuffer byteBuffer=ByteBuffer.allocate(2);byteBuffer.put(tmp);//wrap方式byteBuffer=ByteBuffer.wrap(tmp);//Netty ByteBuf//传统方式(拷贝)ByteBuf byteBuf = Unpooled.buffer();byteBuf.writeBytes(tmp);//wrap方式byteBuf=Unpooled.wrappedBuffer(tmp);

ByteBuf header = Unpooled.wrappedBuffer(tmp);ByteBuf body = Unpooled.wrappedBuffer(tmp);ByteBuf footer = Unpooled.wrappedBuffer(tmp);//不建议的作法ByteBuf wholeBuf = Unpooled.buffer(header.readableBytes() + body.readableBytes()+footer.readableBytes());wholeBuf.writeBytes(header);wholeBuf.writeBytes(body);wholeBuf.writeBytes(footer);//建议使用组合CompositeByteBuf compositeByteBuf=Unpooled.compositeBuffer();//第一个参数increaseWriterIndex,为true会自动增加writerIndexsscompositeByteBuf.addComponents(true,header,body,footer);

ByteBuf byteBuf4slice=.....;ByteBuf header=byteBuf4slice.slice(0,5);ByteBuf body=byteBuf4slice.slice(5,15);ByteBuf footer=byteBuf4slice.slice(15,20);
int loop = 3000000;byte[] content="this is a test".getBytes();//池化bufferlong startTime = System.currentTimeMillis();ByteBuf pooledBuf = null;for (int i = 0; i < loop; i++) { pooledBuf= PooledByteBufAllocator.DEFAULT.buffer(1024); pooledBuf.writeBytes(content); pooledBuf.release();}long pooledTime=System.currentTimeMillis()-startTime;System.out.println("3百万次池化buffer消耗的时间:"+pooledTime);//非池化bufferstartTime = System.currentTimeMillis();ByteBuf unPooledBuf = null;for (int i = 0; i < loop; i++) { unPooledBuf= Unpooled.buffer(1024); unPooledBuf.writeBytes(content); unPooledBuf.release();}long unPooledTime=System.currentTimeMillis()-startTime;System.out.println("3百万次池化buffer消耗的时间:"+unPooledTime);//性能提升System.out.println("池化buffer性能提升:"+Double.valueOf( String.format("%.2f",(unPooledTime-pooledTime)/(double)unPooledTime))*100 +"%");
执行后从输出可见,池化后的buffer性能提升20%左右,非常可观
3百万次池化buffer消耗的时间:7663百万次池化buffer消耗的时间:989
池化buffer性能提升:23.0%
Netty在Java界经之所以久不衰自有它的优势,虽然Netty5夭折了,但Netty4依然足够哦强大,开发者不仅把它用于实现各种通讯应用,还在各种框架中起着顶梁柱的角色,比如阿里的Dubbo。
END




文章转载自石杉的架构笔记,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。





