netty学习及源码分析(一)
一直以来都想要研究下netty,苦于平时工作中很少有用到netty的场景,一直拖到现在才有时间学习一下netty,废话不多说,直接进入正题:
源码查看工具为idea,使用的netty版本为netty4。本节主要分析netty的server端一些简单的源码执行过程分析。
首先,创建netty server时需要先启动一个ServerBootstrap,它的构造方法为:
/**
* Creates a new instance with the specified initial {@link ChannelFactory}.
*/
public ServerBootstrap(ChannelFactory channelFactory) {
super(channelFactory);
}
/**
* Creates a new instance with the specified initial {@link ChannelFactory}.
*/
protected Bootstrap(ChannelFactory channelFactory) {
setFactory(channelFactory);
}
Bootstrap中有个private volatile ChannelFactory factory属性,该属性是用来创建channel使用的。
ChannelFactory有很多实现类,以NioServerSocketChannelFactory为例,其构造方法为:
/**
* Creates a new instance.
*
* @param bossExecutor
* the {@link Executor} which will execute the boss threads
* @param workerExecutor
* the {@link Executor} which will execute the I/O worker threads
* @param workerCount
* the maximum number of I/O worker threads
*/
public NioServerSocketChannelFactory(
Executor bossExecutor, Executor workerExecutor,
int workerCount) {//需要传入两个初始的Executor即需要构造两个线程池,并传入worker的数量
if (bossExecutor == null) {
throw new NullPointerException("bossExecutor");
}
if (workerExecutor == null) {
throw new NullPointerException("workerExecutor");
}
if (workerCount <= 0) {
throw new IllegalArgumentException(
&