netty源码分析持续更新文章,建议先关注收藏哦~以免下次不好找
- netty源码分析之ChannelBuffer
- netty源码分析之Channel接口
- netty源码分析之ServerChannel
- netty源码分析之ChannelConfig
- netty源码分析之ChannelEvent
- netty源码分析之ChannelSink
- netty源码分析之ChannelHandler
- netty源码分析之ChannelPipeline
- netty源码分析之ChannelFuture
- netty源码分析之FrameDecoder
- netty源码分析之FrameDecoder(DelimiterBasedFrameDecoder)
- netty源码分析之FrameDecoder(LengthFieldBasedFrameDecoder)
- netty源码分析之ReplayingDecoder
整体的类图在API文档上已经有了详细的说明:http://netty.io/docs/stable/api/
基本上的类都是继承自AbstractChannelBuffer,其他的都是接口或者工厂类,另外也有部分会实现WrappedChannelBuffer接口。
这里使用了典型的模板模式,AbstractChannelBuffer中会统一负责实现read和write的时候改变readIndex和writeIndex的逻辑,而具体的子类则实现底层的数据拷贝逻辑,比如HeapChannelBuffer和CompositeChannelBuffer(封装了多个Buffer的访问逻辑)
ChannelBuffer和ByteBuffer
ByteBuffer是nio中提供的缓冲区,他设计采用position、limit、capacity、mark等4个属性来表示一个缓冲区;另外还有视图的功能;
如果是非直接缓冲区,那么使用wrap或者allocate创建的都是HeapByteBuffer类型,看了下源码,主要是使用System.arraycopy来作为高效的字节拷贝为get、put、compact等基础操作提供支持。使用ByteBuffer唯一不方便的感觉就是flip()方法,因为只有一个position的设计,在write之后必须调用flip才能调用read。
ChannelBuffer则没有这个问题,API文档上说,相对于ByteBuffer有以下优势:
1.You can define your buffer type if necessary.
2.Transparent zero copy is achieved by built-in composite buffer type.
3.A dynamic buffer type is provided out-of-the-box, whose capacity is expanded on demand, just ike StringBuffer.
4.There’s no need to call the flip() method anymore.
5.It is often faster than ByteBuffer.
3和4都是能够直接带来方便的地方
ChannelBuffer不在是position和limit的架构,而是有以下几个属性
private int readerIndex; private int writerIndex; private int markedReaderIndex; private int markedWriterIndex;
也就是这样
readerIndex和writerIndex都是一开始都是0,随着数据的写入writerIndex会增加,读取数据会使readerIndex增加,但是它不会超过writerIndx,在读取之后,0-readerIndex的就被视为discard的.调用discardReadBytes方法,可以释放这部分空间,他的作用类似ByeBuffer的compact方法;
读和写的时候Index是分开的,因此也就没必要再每次读完以后调用flip方法,另外还有indexOf、bytesBefore等一些方便的方法;DynamicBuffer他的内部还是单独的ChannelBuffer,只是他封装了自动扩容的功能,他会在所以write含义的方法之前检查是否有足够的容量,不足则扩容。
public class DynamicC