一、Channel概述
Channel即Socket封裝,提供了I/O的基本操作。從以下子接口中可以看出Netty對不同的底層協議提供了對應的channel來處理,例如:TCP/IP、UDP/IP、SCTP/IP、HTTP2等。
Channel類圖
Channel子接口
二、實例化流程
從客戶端引導類示例中查看Channel初始化過程。示例中使用NIOSocketChannel作為通信通道,在JAVA中通信中會建立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通過ChannelFactory創建,下面看一下ChannelFactory類圖。
ChannelFactory類圖
ReflectiveChannelFactory提供了newChannel()方法通過反射實例化。示例中通過b.channel(NioSocketChannel.class)將NioSocketChannel.class賦值給ReflectiveChannelFactory的成員變量Constructor<? extends T> constructor,Channel在connect的時候實例化,下面為實例化調用鏈路。
Channel實例化鏈路
三、實例化過程
1.客戶端實例化過程
了解了Channel初始化調用鏈,再來看下以NioSocketChannel為例初始化做了哪些事情。下面是NioSocketChannel的四個構造重載方法。
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 默認使用SelectorProvider.provider()
@2 使用Provider創建SocketChannel。provider.openSocketChannel()->new SocketChannelImpl(this)。
@3 設置NioChannel非阻塞模式
小結:客戶端NioSocketChannel實例化過程中已經回到所熟悉的java nio。創建了通道SocketChannel,并設置為非阻塞。
2.服務端實例化過程
Channel服務端的實例化流程與客戶端是相同的,下面以NioServerSocketChannel為例走查實例化過程。服務端引導初始化示例代碼如下。
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的構造方法。
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 使用默認Provider類SelectorProvider
@2 開啟服務端通道ServerSocketChannel。provider.openServerSocketChannel()->new ServerSocketChannelImpl(this)
@3 將ServerSocketChanne設置為非阻塞
小結:服務端NioServerSocketChannel的實例化過程同樣回到熟悉的Java NIO,創建非阻塞ServerSocketChanne通道。
3.實例化其他事項
在實例化的過程中,會調父類的構造方法super(parent)。
protected AbstractChannel(Channel parent) {
this.parent = parent;
id = newId(); // @1
unsafe = newUnsafe(); // @2
pipeline = newChannelPipeline(); // @3
}
@1 ChannelId初始化
ChannelId是Channel的唯一標識,下面看下DefaultChannelId的生成規則。
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);
}
小結:默認的ChannelId由machineId、processId、sequence、timestamp、random構成。machineId:可以由參數io.netty.machineId自定義,默認為8位隨機byte構成
processId:可以由參數io.netty.processId自定義,默認為4位進程ID
sequence:原子自增序號AtomicInteger,每創建一個Chanenl會進行自增
timestamp:8位的timestamp
random:4位的隨機整數
@2 unsafe初始化
unsafe即I/O的核心操作,byte的讀寫都靠它來處理。服務端NioServerSocketChannel初始化使用NioMessageUnsafe。客戶端NioSocketChannel初始化使用NioSocketChannelUnsafe。以NIO為例看下Unsafe的類圖結構。
unsafe類圖結構
@3 ChannelPipeline初始化
默認使用DefaultChannelPipeline,從構造方法可以看出為鏈表結構,詳細分析另文分析。
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;
}