Netty源码剖析——启动过程源码剖析(二十六)

指南

在 io.netty.example 包下,有很多Netty源码案例,比较适合分析

Netty启动过程源码剖析

  1. 源码需要剖析到Netty调用doBind(),追踪到NioServerSocketChannel的doBind()。
  2. 并且要Debug程序到NioEventLoop类的run(),无限循环,在服务器端运行。

demo 源码EchoServer类的基本理解

java 复制代码
*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.guokai.netty.source.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

/**
 * Echoes back any received data from a client.
 */
public final class EchoServer {

    static final boolean SSL = System.getProperty("ssl") != null;
    static final int PORT = Integer.parseInt(System.getProperty("port", "8007"));

    public static void main(String[] args) throws Exception {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else {
            sslCtx = null;
        }

        // Configure the server.
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .option(ChannelOption.SO_BACKLOG, 100)
             .handler(new LoggingHandler(LogLevel.INFO))
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ChannelPipeline p = ch.pipeline();
                     if (sslCtx != null) {
                         p.addLast(sslCtx.newHandler(ch.alloc()));
                     }
                     //p.addLast(new LoggingHandler(LogLevel.INFO));
                     p.addLast(new EchoServerHandler());
                 }
             });

            // Start the server.
            ChannelFuture f = b.bind(PORT).sync();

            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

说明:

  • 先看启动类: main 方法中,首先创建了关于 SSL 的配置类。

  • 重点分析下创建了两个 EventLoopGroup 对象:

    1. EventloopGroup bossGroup = new NioEventl.oopGroup(1).
    2. EventLoopGroup workerGroup = new NioEventloopGroup( ).
  • 这两个对象是整个Netty的核心对象,可以说整个Netty的运作都依赖于他们。bossGroup 用于接受Tcp 请求,他会将请求交给 wokerGroup ,workerGroup 会获取到真正的连接,然后和连接进行通信,比如读写解码编码等操作。

  • EventLoopGroup是事件循环组(线程组) 有多个 EventLoop,可以注册 channel ,用于在事件循环中去进行选择(和选择器相关)。[debug 看]

  • new NioEventLoopGroup(l); 这个 1 表示 bossGroup 事件组有 1 个线程你可以指定,如果 newNioEventLoopGroup()会含有默认线程个数为(cpu 核数*2),即可以充分的利用多核的优势,[可以 dubug 一把]

    1. DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt("io.netty.eventLoopThreads",NettyRuntime.availableProcessors() * 2));

    2. 会创建 EventExecutor 数组 children =new EventExecutor(nThreads];//debug -下

    3. 每个元素的类型就是 NIOEventLoop, NIOEventLoop实现了EventLoop接口和Executor 接口

  • Try块中创建了一个ServerBootstrap对象,他是一个引导类,用于启动服务器和引导整个程序的初始化(看下源try码 allows easy bootstrap of{@link ServerChannel} ) 。它和 ServerChannel 关联,而 ServerChannel 继承了Channel,有一些方法 remoteAddress 等[可以Debug 下]

  • 随后,变量 b 调用了 group 方法将两个 group 放入了自己的字段中,用于后期引导使用[debug 下 group 方法】

  • 然后添加了一个 channel,其中参数一个 Class 对象,引导类将通过这个 Class 对象反射创建ChannelFactory。然后添加了一些 TCP 的参数。[说明: Channel 的创建在 bind 方法,可以 Debug 下 bind ,会找到 channel = channelFactory.newChannel(); ]

  • 再添加了一个服务器专属的日志处理器 handler。

  • 再添加一个 SocketChannel (不是 ServerSocketChannel) 的 handler。

  • 然后绑定端口并阻塞至连接成功。

  • 最后 main 线程阻塞等待关闭。

  • finally 块中的代码将在服务器关闭时优雅关闭所有资源

相关推荐
重生之我在20年代敲代码22 分钟前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
爱上语文24 分钟前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
serve the people27 分钟前
springboot 单独新建一个文件实时写数据,当文件大于100M时按照日期时间做文件名进行归档
java·spring boot·后端
qmx_071 小时前
HTB-Jerry(tomcat war文件、msfvenom)
java·web安全·网络安全·tomcat
为风而战1 小时前
IIS+Ngnix+Tomcat 部署网站 用IIS实现反向代理
java·tomcat
编程零零七3 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
技术无疆3 小时前
快速开发与维护:探索 AndroidAnnotations
android·java·android studio·android-studio·androidx·代码注入
2401_858286113 小时前
52.【C语言】 字符函数和字符串函数(strcat函数)
c语言·开发语言
铁松溜达py4 小时前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
everyStudy4 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript