nio server启动的第一步,都是要创建一个serverSocketChannel,我截取一段启动代码,一步步分析:

public void afterPropertiesSet() throws Exception {
// 创建rpc工厂
ThreadFactory threadRpcFactory = new NamedThreadFactory("NettyRPC ThreadFactory");
//执行worker线程池数量
int parallel = Runtime.getRuntime().availableProcessors() * 2;
// boss
EventLoopGroup boss = new NioEventLoopGroup(1);
// worker
EventLoopGroup worker = new NioEventLoopGroup(parallel,threadRpcFactory, SelectorProvider.provider());
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)
.childHandler(new MessageRecvChannelInitializer(handlerMap))
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true); ChannelFuture future = bootstrap.bind(serverAddress, Integer.valueOf(port)).sync();
System.out.printf("[author chenjianye] Netty RPC Server start success ip:%s port:%s\n", serverAddress, port); // 注册zookeeper服务
serviceRegistry.register(serverAddress + ":" + port);
// wait
future.channel().closeFuture().sync();
} finally {
worker.shutdownGracefully();
boss.shutdownGracefully();
}
}
入口就在
ChannelFuture future = bootstrap.bind(serverAddress, Integer.valueOf(port)).sync();

顺序往下执行,直到AbstractBootstrap类的doBind方法:
private ChannelFuture doBind(final SocketAddress localAddress) {
final ChannelFuture regFuture = this.initAndRegister();
final Channel channel = regFuture.channel();
if(regFuture.cause() != null) {
return regFuture;
} else if(regFuture.isDone()) {
ChannelPromise promise1 = channel.newPromise();
doBind0(regFuture, channel, localAddress, promise1);
return promise1;
} else {
final AbstractBootstrap.PendingRegistrationPromise promise = new AbstractBootstrap.PendingRegistrationPromise(channel, null);
regFuture.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) throws Exception {
Throwable cause = future.cause();
if(cause != null) {
promise.setFailure(cause);
} else {
promise.executor = channel.eventLoop();
} AbstractBootstrap.doBind0(regFuture, channel, localAddress, promise);
}
});
return promise;
}
}
=============================================
这个方法需要重点分析,我做个标记,doBind方法分析如下: 1.final ChannelFuture regFuture = this.initAndRegister();
final ChannelFuture initAndRegister() {
// 通过channel工厂反射创建ServerSocketChannel,并创建了作用于serverSocketChannel的channelPipeline管道
// 这个管道维护了ctx为元素的双向链表,到目前为止,pipeline的顺序为:head(outBound) ----> tail(inbound)
Channel channel = this.channelFactory().newChannel(); try {
     // 这个init方法第一个主要是设置channel的属性,我不细说了
// 第二个作用是增加了inbound处理器,channelInitializer,里面有一个initChannel()方法会在特定时刻被触发,什么时候被触发,后面我会说到。
this.init(channel);
} catch (Throwable var3) {
channel.unsafe().closeForcibly();
return (new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE)).setFailure(var3);
}    // 到了这里,就开始执行register逻辑,这个是关键,我把register的代码贴出来,跟着后面的代码继续看,跳转到2。
ChannelFuture regFuture = this.group().register(channel);
if(regFuture.cause() != null) {
if(channel.isRegistered()) {
channel.close();
} else {
channel.unsafe().closeForcibly();
}
} return regFuture;
}
2.AbstractChannel里的register方法:
public final void register(EventLoop eventLoop, final ChannelPromise promise) {
if(eventLoop == null) {
throw new NullPointerException("eventLoop");
} else if(AbstractChannel.this.isRegistered()) {
promise.setFailure(new IllegalStateException("registered to an event loop already"));
} else if(!AbstractChannel.this.isCompatible(eventLoop)) {
promise.setFailure(new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName()));
} else {
AbstractChannel.this.eventLoop = eventLoop;
// 到这里还是主线程启动,所以会执行else,启动了boss线程,register0方法跳转到3
if(eventLoop.inEventLoop()) {
this.register0(promise);
} else {
try {
eventLoop.execute(new OneTimeTask() {
public void run() {
AbstractUnsafe.this.register0(promise);
}
});
} catch (Throwable var4) {
AbstractChannel.logger.warn("Force-closing a channel whose registration task was not accepted by an event loop: {}", AbstractChannel.this, var4);
this.closeForcibly();
AbstractChannel.this.closeFuture.setClosed();
this.safeSetFailure(promise, var4);
}
} }
}
3.register0方法
private void register0(ChannelPromise promise) {
try {
if(!promise.setUncancellable() || !this.ensureOpen(promise)) {
return;
} boolean t = this.neverRegistered;
// 这个方法主要是 this.selectionKey = this.javaChannel().register(this.eventLoop().selector, 0, this);
        AbstractChannel.this.doRegister();
this.neverRegistered = false;
AbstractChannel.this.registered = true; // 回调之前doBind方法的listener,boss线程添加了新的任务:bind任务
this.safeSetSuccess(promise); // 这个方法东西内容很多
// 第一步:this.head.fireChannelRegistered()没有什么实质内容,最终执行到inbound的next.invokeChannelRegistered()方法
// 第二步:根据上文,目前的pipeline顺序为head---->initializer---->tail
// 第三步:执行initializer
// 第四步:添加一个新的inbound处理器,ServerBootstrapAcceptor,此时的顺序为:head---->initizlizer---->ServerBootstrapAcceptor---->tail
// 第五步:移除initizlizer,此时pipeline顺序为:head---->ServerBootstrapAcceptor---->tail
// 第六步:么有什么实质内容,这个方法就算执行结束了
AbstractChannel.this.pipeline.fireChannelRegistered(); // 这里channel还没有绑定,所以isActive()方法返回false,不会继续执行,目前boss线程还剩下bind任务
if(t && AbstractChannel.this.isActive()) {
AbstractChannel.this.pipeline.fireChannelActive();
}
} catch (Throwable var3) {
this.closeForcibly();
AbstractChannel.this.closeFuture.setClosed();
this.safeSetFailure(promise, var3);
} }
4.bind任务
bind任务是一个outbound,所以会按照tail---->head的顺序执行,目前只有head是outbound。
headHandler最终会执行AbstractUnsafe的bind方法:
AbstractChannel.this.doBind(localAddress);
public final void bind(SocketAddress localAddress, ChannelPromise promise) {
if(promise.setUncancellable() && this.ensureOpen(promise)) {
if(Boolean.TRUE.equals(AbstractChannel.this.config().getOption(ChannelOption.SO_BROADCAST)) && localAddress instanceof InetSocketAddress && !((InetSocketAddress)localAddress).getAddress().isAnyLocalAddress() && !PlatformDependent.isWindows() && !PlatformDependent.isRoot()) {
AbstractChannel.logger.warn("A non-root user can\'t receive a broadcast packet if the socket is not bound to a wildcard address; binding to a non-wildcard address (" + localAddress + ") anyway as requested.");
} boolean wasActive = AbstractChannel.this.isActive(); try {
       //由于我们是nioServerSocketChannel,所以:this.javaChannel().socket().bind(localAddress, this.config.getBacklog()); AbstractChannel.this.doBind(localAddress); } catch (Throwable var5) {
            this.safeSetFailure(promise, var5);
this.closeIfClosed();
return;
}      // 此时已经绑定了,所以isActive()返回true,执行
if(!wasActive && AbstractChannel.this.isActive()) {
// 重新往boss线程加入了任务
this.invokeLater(new OneTimeTask() {
public void run() {
AbstractChannel.this.pipeline.fireChannelActive();
}
});
} this.safeSetSuccess(promise);
}
}
public ChannelPipeline fireChannelActive() {
// 来回调用,貌似这里没有什么实质内容
this.head.fireChannelActive();
if(this.channel.config().isAutoRead()) {
// 这个是outBound,最终会触发head
     // head会执行 this.unsafe.beginRead(),最终会执行abstractNioChannel里的doBeginRead()方法,最终会执行到5
        this.channel.read();
} return this;
}
5.
protected void doBeginRead() throws Exception {
if(!this.inputShutdown) {
SelectionKey selectionKey = this.selectionKey;
if(selectionKey.isValid()) {
this.readPending = true;
int interestOps = selectionKey.interestOps();
if((interestOps & this.readInterestOp) == 0) {
selectionKey.interestOps(interestOps | this.readInterestOp);
} }
}
}
终于看到我们熟悉的东西了,最终把selectionKey的interestOps设置为SelectionKey.OP_ACCEPT。
												

netty源码分析之一:server的启动的更多相关文章

  1. Netty源码分析之服务端启动过程

    一.首先来看一段服务端的示例代码: public class NettyTestServer { public void bind(int port) throws Exception{ EventL ...

  2. Netty源码分析之服务端启动

    Netty服务端启动代码: public final class EchoServer { static final int PORT = Integer.parseInt(System.getPro ...

  3. Netty源码—一、server启动(1)

    Netty作为一个Java生态中的网络组件有着举足轻重的位置,各种开源中间件都使用Netty进行网络通信,比如Dubbo.RocketMQ.可以说Netty是对Java NIO的封装,比如ByteBu ...

  4. Netty源码分析第1章(Netty启动流程)---->第1节: 服务端初始化

    Netty源码分析第一章:  Server启动流程 概述: 本章主要讲解server启动的关键步骤, 读者只需要了解server启动的大概逻辑, 知道关键的步骤在哪个类执行即可, 并不需要了解每一步的 ...

  5. Netty源码分析第1章(Netty启动流程)---->第2节: NioServerSocketChannel的创建

    Netty源码分析第一章:  Server启动流程 第二节:NioServerSocketChannel的创建 我们如果熟悉Nio, 则对channel的概念则不会陌生, channel在相当于一个通 ...

  6. Netty源码分析第1章(Netty启动流程)---->第5节: 绑定端口

    Netty源码分析第一章:Netty启动步骤 第五节:绑定端口 上一小节我们学习了channel注册在selector的步骤, 仅仅做了注册但并没有监听事件, 事件是如何监听的呢? 我们继续跟第一小节 ...

  7. Netty源码分析第2章(NioEventLoop)---->第4节: NioEventLoop线程的启动

    Netty源码分析第二章: NioEventLoop   第四节: NioEventLoop线程的启动 之前的小节我们学习了NioEventLoop的创建以及线程分配器的初始化, 那么NioEvent ...

  8. Netty源码分析 (三)----- 服务端启动源码分析

    本文接着前两篇文章来讲,主要讲服务端类剩下的部分,我们还是来先看看服务端的代码 /** * Created by chenhao on 2019/9/4. */ public final class ...

  9. Netty源码分析第1章(Netty启动流程)---->第3节: 服务端channel初始化

    Netty源码分析第一章:Netty启动流程   第三节:服务端channel初始化 回顾上一小节的initAndRegister()方法: final ChannelFuture initAndRe ...

  10. Netty源码分析第1章(Netty启动流程)---->第4节: 注册多路复用

    Netty源码分析第一章:Netty启动流程   第四节:注册多路复用 回顾下以上的小节, 我们知道了channel的的创建和初始化过程, 那么channel是如何注册到selector中的呢?我们继 ...

随机推荐

  1. js前端使用jOrgChart插件实现组织架构图的展示

    项目要做组织架构图,要把它做成自上而下的树形结构. 需要购买阿里云产品的,可以点击此链接购买,有红包优惠哦: https://promotion.aliyun.com/ntms/yunparter/i ...

  2. textarea 标签的使用

    <textarea rows="行数" cols="列数">默认出现文本</textarea> 阻止拉伸:style="res ...

  3. Go 初体验 - 令人惊叹的语法 - defer.4 - defer 对宿主函数返回值的影响

    defer 函数可以影响宿主函数的返回值 看代码: 调用: 输出: 结果又让人意外了. coo1:因为传引用,return 时 i = 100, return 返回的也是 100,return 执行之 ...

  4. Python之猴子补丁

    1.在运行时,对属性,方法,函数等进行动态替换 2.其目的往往是为了通过替换,修改来增强,扩展原有代码的能力 #test2.py class Person: def get_score(self): ...

  5. UI框架搭建DAY1

    分析:UI框架主要是为了用户(使用框架的程序猿)更快捷.方便地开发UI,UI框架的好处还在于解耦,使得程序更具有灵活性. UI框架的核心是窗口的管理,窗口管理的主要任务就是显示窗口和关闭窗口. 因为窗 ...

  6. highChart 缺值-曲线断开问题

    time =item.datetime; aqi = Number(item.aqi); pm2_5 = Number(item.pm25); pm10 = Number(item.pm10); co ...

  7. week_one-python基础 列表 增删改查

    # Author:larlly #列表增删改查#定义列表name = ["wo","ni","ta","wo"] #定义 ...

  8. MVC开发模式的数据运行流程

    对于java中经典的开发模式MVC,有一些感触!现说一下Java中数据的运行流程,由于我技术有限,有错的话欢迎提出,不喜勿喷! 我们知道在MVC开发模式,包括三部分视图层V(view).控制层C(Co ...

  9. 5、Spring-Kafka3

    3. Introduction This first part of the reference documentation is a high-level overview of Spring fo ...

  10. Codeforces Round #505 (Div 1 + Div 2 Combined) Solution

    从这里开始 题目列表 瞎扯 Problem A Doggo Recoloring Problem B Weakened Common Divisor Problem C Plasticine zebr ...