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. IdentityServer4授权和认证集成Identity和profile

    identiyt的使用可以看之前的文章:https://www.cnblogs.com/nsky/p/10323415.html 之前的ids4授权服务器都是用的in-men方式把数据添加到内存, 现 ...

  2. HBase笔记6 过滤器

    过滤器 过滤器是GET或者SCAN时过滤结果用的,相当于SQL的where语句 HBase中的过滤器创建后会被序列化,然后分发到各个region server中,region server会还原过滤器 ...

  3. 最小生成树模板题 hpu 积分赛 Vegetable and Road again

    问题 H: Vegetable and Road again 时间限制: 1 Sec 内存限制: 128 MB 提交: 19 解决: 8 题目描述 修路的方案终于确定了.市政府要求任意两个公园之间都必 ...

  4. CentOS 7 MariaDB-MMM

    MariaDB-MMM高可用群集 1.MySQL-MMM概述 MMM(Master-Master replication manager for MySQL)是一套支持双主故障切换和双主日常管理的脚本 ...

  5. Python之socket_tcp

    1.1socket编程之tcp编程 """ socket类型 sock_stream 面向连接的流套接字,默认值 tcp协议 sock_dgram 无连接的数据报文套接字 ...

  6. 移动端长按响应事件以及阻止默认行为e.preventDefault()导致定时器setTimeout不能响应

    手指触摸绑定: $(document).on('touchstart', '.photo', function(e){ currentIndex = parseInt($(this).index('. ...

  7. “==”和equals

    == 比较的是变量(栈)内存中存放的对象的(堆)内存地址,用来判断两个对象的地址是否相同,即是否是指相同一个对象.比较的是真正意义上的指针操作. 1.比较的是操作符两端的操作数是否是同一个对象.2.两 ...

  8. 第六节 DOM操作应用

    创建.插入和删除元素 创建DOM元素: createElement(标签名); //创建一个节点 appendChild(节点); //追加一个节点 例如:document.body.appendCh ...

  9. zabbix 乱码问题

    一.乱码原因 查看cpu负载,中文乱码如下 这个问题是由于zabbix的web端没有中文字库,我们最需要把中文字库加上即可 二.解决zabbix乱码方法 2.1 上传字体文件到zabbix中 找到本地 ...

  10. python爬虫——绕开杂乱无章的代码和堵住请求的302异常(2)

    淘宝那次抓包,居然发现不了要抓的url位置,三星中... 不过不怕,不就是没法快点分析出包嘛,下次用phantomJS硬杠,或者有时间慢慢分析也好. 今天挑战一个稍微好爬的网站:狗搬家(误) 打开后台 ...