上一篇粗略的介紹了一下netty,本篇將詳細介紹Netty的服務器的啓動過程。java
看過上篇事例的人,能夠知道ServerBootstrap
是Netty服務端啓動中扮演着一個重要的角色。 它是Netty提供的一個服務端引導類,繼承自AbstractBootstrap
。
ServerBootstrap
主要包括兩部分:bossGroup
和workerGroup
。其中bossGroup
主要用於綁定端口,接收來自客戶端的請求,接收到請求以後,就會把這些請求交給workGroup
去處理。就像現實中的老闆和員工同樣,本身開個公司(綁定端口),到外面接活(接收請求),使喚員工幹活(讓worker去處理)。git
端口綁定以前,會先check引導類(ServerBootstrap)的bossGroup和workerGroup有沒有設置,以後再調用doBind。github
private ChannelFuture doBind(final SocketAddress localAddress) {
// 初始化並註冊一個channel,並將chanelFuture返回
final ChannelFuture regFuture = initAndRegister();
// 獲得實際的channel(初始化和註冊的動做可能還沒有完成)
final Channel channel = regFuture.channel();
// 發生異常時,直接返回
if (regFuture.cause() != null) {
return regFuture;
}
// 當到這chanel相關處理已經完成時
if (regFuture.isDone()) {
// 到這能夠肯定channel已經註冊成功
ChannelPromise promise = channel.newPromise();
// 進行相關的綁定操做
doBind0(regFuture, channel, localAddress, promise);
return promise;
} else {
// 註冊通常到這就已經完成,到以防萬一
final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
// 添加一個監聽器
regFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
Throwable cause = future.cause();
if (cause != null) {
promise.setFailure(cause);
} else {
// 修改註冊狀態爲成功(當註冊成功時不在使用全局的executor,使用channel本身的,詳見 https://github.com/netty/netty/issues/2586)
promise.registered();
// 進行相關的綁定操做
doBind0(regFuture, channel, localAddress, promise);
}
}
});
return promise;
}
}
複製代碼
上面的代碼主要有兩部分:初始化並註冊一個channel和綁定端口。promise
final ChannelFuture initAndRegister() {
Channel channel = null;
try {
// 生產各新channel
channel = channelFactory.newChannel();
// 初始化channel
init(channel);
} catch (Throwable t) {
if (channel != null) {
// 註冊失敗時強制關閉
channel.unsafe().closeForcibly();
// 因爲channel還沒有註冊好,強制使用GlobalEventExecutor
return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
}
return new DefaultChannelPromise(new FailedChannel(), GlobalEventExecutor.INSTANCE).setFailure(t);
}
// 註冊channel
ChannelFuture regFuture = config().group().register(channel);
if (regFuture.cause() != null) {
if (channel.isRegistered()) {
channel.close();
} else {
channel.unsafe().closeForcibly();
}
}
return regFuture;
}
複製代碼
channel的初始化方法:bash
void init(Channel channel) throws Exception {
// 獲取bossChannel的可選項Map
final Map<ChannelOption<?>, Object> options = options0();
synchronized (options) {
setChannelOptions(channel, options, logger);
}
// 獲取bossChannel的屬性Map
final Map<AttributeKey<?>, Object> attrs = attrs0();
synchronized (attrs) {
for (Entry<AttributeKey<?>, Object> e : attrs.entrySet()) {
@SuppressWarnings("unchecked")
AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
channel.attr(key).set(e.getValue());
}
}
ChannelPipeline p = channel.pipeline();
// 設置worker的相關屬性
final EventLoopGroup currentChildGroup = childGroup;
final ChannelHandler currentChildHandler = childHandler;
final Entry<ChannelOption<?>, Object>[] currentChildOptions;
final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
synchronized (childOptions) {
currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size()));
}
synchronized (childAttrs) {
currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size()));
}
p.addLast(new ChannelInitializer<Channel>() {
@Override
public void initChannel(final Channel ch) throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
// 添加handler到pipeline
ChannelHandler handler = config.handler();
if (handler != null) {
pipeline.addLast(handler);
}
// 經過EventLoop將ServerBootstrapAcceptor到pipeline中,保證它是最後一個handler
ch.eventLoop().execute(new Runnable() {
@Override
public void run() {
pipeline.addLast(new ServerBootstrapAcceptor(
ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
}
});
}
});
}
複製代碼
channel的註冊方法,最終是調用doRegister,不一樣的channel有所不一樣,下面以Nio爲例:服務器
protected void doRegister() throws Exception {
boolean selected = false;
for (; ; ) {
try {
// 直接調用java的提供的Channel的註冊方法
selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 0, this);
return;
} catch (CancelledKeyException e) {
if (!selected) {
eventLoop().selectNow();
selected = true;
} else {
throw e;
}
}
}
}
複製代碼
最終調用的是NioServerSocketChannel的doBind方法。app
protected void doBind(SocketAddress localAddress) throws Exception {
if (PlatformDependent.javaVersion() >= 7) {
javaChannel().bind(localAddress, config.getBacklog());
} else {
javaChannel().socket().bind(localAddress, config.getBacklog());
}
}
複製代碼
到這就完成了netty服務端的整個啓動過程。socket
文中帖的代碼註釋全在:github.com/KAMIJYOUDOU… , 有興趣的童鞋能夠關注一下。ide