一、Channel概述
Channel即Socket封裝,提供了I/O的基本操作。從以下子接口中可以看出Netty對(duì)不同的底層協(xié)議提供了對(duì)應(yīng)的channel來(lái)處理,例如:TCP/IP、UDP/IP、SCTP/IP、HTTP2等。
Channel類圖
Channel子接口
二、實(shí)例化流程
從客戶端引導(dǎo)類示例中查看Channel初始化過(guò)程。示例中使用NIOSocketChannel作為通信通道,在JAVA中通信中會(huì)建立socket連接。
EventLoopGroup workerGroup = new NioEventLoopGroup();
Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.remoteAddress(HOST, PORT);
b.handler(initializer);
Channel channel = b.connect().syncUninterruptibly().channel();
Channel通過(guò)ChannelFactory創(chuàng)建,下面看一下ChannelFactory類圖。
ChannelFactory類圖
ReflectiveChannelFactory提供了newChannel()方法通過(guò)反射實(shí)例化。示例中通過(guò)b.channel(NioSocketChannel.class)將NioSocketChannel.class賦值給ReflectiveChannelFactory的成員變量Constructor<? extends T> constructor,Channel在connect的時(shí)候?qū)嵗?,下面為?shí)例化調(diào)用鏈路。
Channel實(shí)例化鏈路
三、實(shí)例化過(guò)程
1.客戶端實(shí)例化過(guò)程
了解了Channel初始化調(diào)用鏈,再來(lái)看下以NioSocketChannel為例初始化做了哪些事情。下面是NioSocketChannel的四個(gè)構(gòu)造重載方法。
public NioSocketChannel() {
this(DEFAULT_SELECTOR_PROVIDER); // @1
}
public NioSocketChannel(SelectorProvider provider) {
this(newSocket(provider)); // @2
}
public NioSocketChannel(SocketChannel socket) {
this(null, socket);
}
public NioSocketChannel(Channel parent, SocketChannel socket) {
super(parent, socket);
config = new NioSocketChannelConfig(this, socket.socket());
}
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
super(parent);
this.ch = ch;
this.readInterestOp = readInterestOp;
ch.configureBlocking(false); // @3
}
}
代碼解讀
@1 默認(rèn)使用SelectorProvider.provider()
@2 使用Provider創(chuàng)建SocketChannel。provider.openSocketChannel()->new SocketChannelImpl(this)。
@3 設(shè)置NioChannel非阻塞模式
小結(jié):客戶端NioSocketChannel實(shí)例化過(guò)程中已經(jīng)回到所熟悉的java nio。創(chuàng)建了通道SocketChannel,并設(shè)置為非阻塞。
2.服務(wù)端實(shí)例化過(guò)程
Channel服務(wù)端的實(shí)例化流程與客戶端是相同的,下面以NioServerSocketChannel為例走查實(shí)例化過(guò)程。服務(wù)端引導(dǎo)初始化示例代碼如下。
EventLoopGroup group = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.option(ChannelOption.SO_BACKLOG, 1024);
b.group(group)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new Http2ServerInitializer(sslCtx));
Channel ch = b.bind(PORT).sync().channel();
NioServerSocketChannel的構(gòu)造方法。
public NioServerSocketChannel() {
this(newSocket(DEFAULT_SELECTOR_PROVIDER)); // @1
}
public NioServerSocketChannel(SelectorProvider provider) {
this(newSocket(provider)); // @2
}
public NioServerSocketChannel(ServerSocketChannel channel) {
super(null, channel, SelectionKey.OP_ACCEPT);
config = new NioServerSocketChannelConfig(this, javaChannel().socket());
}
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
super(parent);
this.ch = ch;
this.readInterestOp = readInterestOp;
ch.configureBlocking(false); // @3
}
代碼解讀
@1 使用默認(rèn)Provider類SelectorProvider
@2 開(kāi)啟服務(wù)端通道ServerSocketChannel。provider.openServerSocketChannel()->new ServerSocketChannelImpl(this)
@3 將ServerSocketChanne設(shè)置為非阻塞
小結(jié):服務(wù)端NioServerSocketChannel的實(shí)例化過(guò)程同樣回到熟悉的Java NIO,創(chuàng)建非阻塞ServerSocketChanne通道。
3.實(shí)例化其他事項(xiàng)
在實(shí)例化的過(guò)程中,會(huì)調(diào)父類的構(gòu)造方法super(parent)。
protected AbstractChannel(Channel parent) {
this.parent = parent;
id = newId(); // @1
unsafe = newUnsafe(); // @2
pipeline = newChannelPipeline(); // @3
}
@1 ChannelId初始化
ChannelId是Channel的唯一標(biāo)識(shí),下面看下DefaultChannelId的生成規(guī)則。
private DefaultChannelId() {
data = new byte[macHINE_ID.length + PROCESS_ID_LEN + SEQUENCE_LEN + TIMESTAMP_LEN + RANDOM_LEN];
int i = 0;
// machineId
System.arraycopy(MACHINE_ID, 0, data, i, MACHINE_ID.length);
i += MACHINE_ID.length;
// processId
i = writeInt(i, PROCESS_ID);
// sequence
i = writeInt(i, nextSequence.getAndIncrement());
// timestamp (kind of)
i = writeLong(i, Long.reverse(System.nanoTime()) ^ System.currentTimeMillis());
// random
int random = PlatformDependent.threadLocalRandom().nextInt();
i = writeInt(i, random);
assert i == data.length;
hashCode = Arrays.hashCode(data);
}
小結(jié):默認(rèn)的ChannelId由machineId、processId、sequence、timestamp、random構(gòu)成。machineId:可以由參數(shù)io.netty.machineId自定義,默認(rèn)為8位隨機(jī)byte構(gòu)成
processId:可以由參數(shù)io.netty.processId自定義,默認(rèn)為4位進(jìn)程ID
sequence:原子自增序號(hào)AtomicInteger,每創(chuàng)建一個(gè)Chanenl會(huì)進(jìn)行自增
timestamp:8位的timestamp
random:4位的隨機(jī)整數(shù)
@2 unsafe初始化
unsafe即I/O的核心操作,byte的讀寫都靠它來(lái)處理。服務(wù)端NioServerSocketChannel初始化使用NioMessageUnsafe??蛻舳薔ioSocketChannel初始化使用NioSocketChannelUnsafe。以NIO為例看下Unsafe的類圖結(jié)構(gòu)。
unsafe類圖結(jié)構(gòu)
@3 ChannelPipeline初始化
默認(rèn)使用DefaultChannelPipeline,從構(gòu)造方法可以看出為鏈表結(jié)構(gòu),詳細(xì)分析另文分析。
protected DefaultChannelPipeline(Channel channel) {
this.channel = ObjectUtil.checkNotNull(channel, "channel");
succeededFuture = new SucceededChannelFuture(channel, null);
voidPromise = new VoidChannelPromise(channel, true);
tail = new TailContext(this);
head = new HeadContext(this);
head.next = tail;
tail.prev = head;
}






