以netty提供的echo server作为分析入口,echoServer代码:
- public void run() {
- // 构造NioServerSocketChannelFactory,初始化bootstrap
- ServerBootstrap bootstrap = new ServerBootstrap(
- new NioServerSocketChannelFactory(
- Executors.newCachedThreadPool(),
- Executors.newCachedThreadPool()));
- // 创建一个自定义的PipelineFactory
- bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
- public ChannelPipeline getPipeline() throws Exception {
- return Channels.pipeline(new EchoServerHandler());
- }
- });
- // 开始bind端口,启动server
- bootstrap.bind(new InetSocketAddress(port));
- }
public void run() {
// 构造NioServerSocketChannelFactory,初始化bootstrap
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// 创建一个自定义的PipelineFactory
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() throws Exception {
return Channels.pipeline(new EchoServerHandler());
}
});
// 开始bind端口,启动server
bootstrap.bind(new InetSocketAddress(port));
}
Server启动过程:
一.ServerBootstrap配置,NioServerSocketChannelFactory初始化
1. 构造NioWorkerPool,启动worker线程,默认个数CPU*2
- public NioServerSocketChannelFactory(
- Executor bossExecutor, Executor workerExecutor,
- int workerCount) {
- this(bossExecutor, new NioWorkerPool(workerExecutor, workerCount));
- }
public NioServerSocketChannelFactory(
Executor bossExecutor, Executor workerExecutor,
int workerCount) {
this(bossExecutor, new NioWorkerPool(workerExecutor, workerCount));
}
2.创建worker数组
- workers = new AbstractNioWorker[workerCount];
- for (int i = 0; i < workers.length; i++) {
- workers[i] = createWorker(workerExecutor);
- }
- this.workerExecutor = workerExecutor;
workers = new AbstractNioWorker[workerCount];
for (int i = 0; i < workers.length; i++) {
workers[i] = createWorker(workerExecutor);
}
this.workerExecutor = workerExecutor;
- protected NioWorker createWorker(Executor executor) {
- return new NioWorker(executor);
- }
protected NioWorker createWorker(Executor executor) {
return new NioWorker(executor);
}
3.打开选择器
- AbstractNioWorker(Executor executor) {
- this.executor = executor;
- openSelector();
AbstractNioWorker(Executor executor) {
this.executor = executor;
openSelector();
}
4. 启动worker线程
- selector = Selector.open();
- ....
- DeadLockProofWorker.start(executor, new ThreadRenamingRunnable(this, "New I/O worker #" + id));
- ...
selector = Selector.open();
....
DeadLockProofWorker.start(executor, new ThreadRenamingRunnable(this, "New I/O worker #" + id));
...
5.初始化NioServerSocketPipelineSink,将workerPool注册到PipelineSink中