古道长亭

Contact me with ixiaoqiang0011@gmail.com


  • 首页

  • 归档

  • 分类

  • 关于

  • Book

  • 搜索

Netty源码剖析

时间: 2022-07-25   |   分类: RPC框架   netty   | 字数: 619 字 | 阅读约: 2分钟 | 阅读次数:

Netty源码剖析

1.源码构建

https://github.com/netty/netty 源码地址

源码包 example里有常用示例代码。

2.EventLoopGroup事件循环组(线程组)源码

EventLoopGroup 是一组 EventLoop 的抽象,Netty 为了更好的利用多核 CPU 资源,一般会有多个 EventLoop 同时工作,每个 EventLoop 维护着一个 Selector 实例。

线程组源码流程分析:

线程组源码主要源码跟踪:

NioEventLoopGroup线程组的创建

private static final int DEFAULT_EVENT_LOOP_THREADS;
//默认线程数量为处理器数*2
static {
  DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
    "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

  if (logger.isDebugEnabled()) {
    logger.debug("-Dio.netty.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS);
  }
}

/**
     * @see MultithreadEventExecutorGroup#MultithreadEventExecutorGroup(int, Executor, Object...)
     */
protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
  super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
}

NioEventLoop的创建

private final EventExecutor[] children;				

//根据线程数量创建
children = new EventExecutor[nThreads];

for (int i = 0; i < nThreads; i ++) {
  boolean success = false;
  try {
    //循环创建线程NioEventLoop
    children[i] = newChild(executor, args);
    success = true;
  } catch (Exception e) {
    // TODO: Think about if this is a good exception type
    throw new IllegalStateException("failed to create a child event loop", e);
  } finally {
    if (!success) {
      for (int j = 0; j < i; j ++) {
        children[j].shutdownGracefully();
      }

      for (int j = 0; j < i; j ++) {
        EventExecutor e = children[j];
        try {
          while (!e.isTerminated()) {
            e.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
          }
        } catch (InterruptedException interrupted) {
          // Let the caller handle the interruption.
          Thread.currentThread().interrupt();
          break;
        }
      }
    }
  }
}

newChild方法

#NioEventLoopGroup

@Override
protected EventLoop newChild(Executor executor, Object... args) throws Exception {
  EventLoopTaskQueueFactory queueFactory = args.length == 4 ? (EventLoopTaskQueueFactory) args[3] : null;
  return new NioEventLoop(this, executor, (SelectorProvider) args[0],
                          ((SelectStrategyFactory) args[1]).newSelectStrategy(), (RejectedExecutionHandler) args[2], queueFactory);
}

NioEventLoop

NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider,
                 SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler,
                 EventLoopTaskQueueFactory queueFactory) {
        super(parent, executor, false, newTaskQueue(queueFactory), newTaskQueue(queueFactory),
                rejectedExecutionHandler);
        if (selectorProvider == null) {
            throw new NullPointerException("selectorProvider");
        }
        if (strategy == null) {
            throw new NullPointerException("selectStrategy");
        }
        provider = selectorProvider;
  			//创建选择器
        final SelectorTuple selectorTuple = openSelector();
        selector = selectorTuple.selector;
        unwrappedSelector = selectorTuple.unwrappedSelector;
        selectStrategy = strategy;
    }

3.netty启动源码

启动流程图:

4.BossGroup/WorkGroup/消息入站源码

BossGroup主要负责监听. workGroup负责消息处理. 主要看下BossGroup如何将通道交给workGroup的,和如何处理消息读取的.即入站

#rpc# #socket# #netty#
QQ扫一扫交流

标题:Netty源码剖析

作者:古道长亭

声明: 欢迎加群交流!

如有帮助,欢迎多多交流 ^_^

微信打赏

支付宝打赏

自定义rpc框架
Netty高级应用
  • 文章目录
  • 站点概览
古道长亭

古道长亭

Always remember that your present situation is not your final destination. The best is yet to come.

226 日志
57 分类
104 标签
GitHub Gitee
友情链接
  • 古道长亭的BOOK
  • JAVA学习
标签云
  • Mysql
  • 搜索引擎
  • Mybatis
  • 容器
  • 架构
  • 消息队列
  • Flink
  • Sharding sphere
  • 流处理
  • 缓存
  • 1.源码构建
  • 2.EventLoopGroup事件循环组(线程组)源码
  • 3.netty启动源码
  • 4.BossGroup/WorkGroup/消息入站源码
© 2019 - 2024 京ICP备19012088号-1
0%