/** * Default implementation which uses simple round-robin to choose next {@link EventExecutor}. * 默认使用round-robin算法选择下一个实例的EventExecutor实现 * round-robin:主要用在负载均衡方向,比如有5台机器,第一次分请求到了第一台机器,第二次到了第二台机器,第三次请求到了第三台请求,以此类推一直到第五台机器,然后第六次又到了第一台机器,这样一个轮流的调用,处理负载,这里的Executor数组也是使用这种方式,保证数组里边的EventExecutor被均衡调用。 */ public final class DefaultEventExecutorChooserFactory implements EventExecutorChooserFactory { public EventExecutorChooser newChooser(EventExecutor[] executors) { if (isPowerOfTwo(executors.length)) { return new PowerOfTwoEventExecutorChooser(executors); } else { return new GenericEventExecutorChooser(executors); } }
//伪代码 public abstract class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup { private final EventExecutor[] children; protected MultithreadEventExecutorGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory, Object... args) { children = new EventExecutor[nThreads]; for (int i = 0; i < nThreads; i ++) { children[i] = newChild(executor, args); } chooser = chooserFactory.newChooser(children); } }
children的来源是newChild()方法:
1 2 3 4 5 6 7
/** * Create a new EventExecutor which will later then accessible via the {@link #next()} method. This method will be * called for each thread that will serve this {@link MultithreadEventExecutorGroup}. * 创建一个EventExecutor ,稍后可以调用next()方法,这个next()方法被每个线程调用,这些线程 是服务MultithreadEventExecutorGroup的 */ protected abstract EventExecutor newChild(Executor executor, Object... args) throws Exception;
这个是EventExecutor 的创建,接下来我们看一下register方法,我们打了一个断点:
之后debug进入register方法,我们进入的是SingleThreadEventLoop:
1 2 3 4 5 6 7 8 9 10 11 12
/** * Abstract base class for {@link EventLoop}s that execute all its submitted tasks in a single thread. * EventLoop的基础抽象类,所有提交的任务都会在一个线程里边执行。 * */ public abstract class SingleThreadEventLoop extends SingleThreadEventExecutor implements EventLoop { ...略 public ChannelFuture register(Channel channel) { return register(new DefaultChannelPromise(channel, this)); } ...略 }