# Netty源码剖析


<!--more-->


## 1.源码构建

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

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

## 2.EventLoopGroup事件循环组（线程组）源码

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

**线程组源码流程分析**:

 ![img_30](https://img.zhaojq.top/20260727091750402.png "img_30")

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

NioEventLoopGroup线程组的创建

```java
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的创建

```java
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方法

```java
#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

```java
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启动源码

**启动流程图**：

![img_31](https://img.zhaojq.top/20260727091750602.png "img_31")



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

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

![img_32](https://img.zhaojq.top/20260727091750799.png "img_32")














