服务器启动代码
public class SomeServer {
public static void main(String[] args) throws InterruptedException {
//第一部分
EventLoopGroup parentGroup = new NioEventLoopGroup();
EventLoopGroup childGroup = new NioEventLoopGroup();
try {
//第二部分
ServerBootstrap bootstrap = new ServerBootstrap();
// 将parentGroup、childGroup初始化到bootstrap
bootstrap.group(parentGroup, childGroup)
// 将指定类型的channel的工厂类初始化到bootstrap
.channel(NioServerSocketChannel.class)
.attr(AttributeKey.valueOf("depart"), "行政部")
.childAttr(AttributeKey.valueOf("addr"), "北京海淀")
// 添加日志处理器
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new StringDecoder());
}
});
//第三部分
ChannelFuture future = bootstrap.bind(8888).sync();
System.out.println("服务器已启动。。。");
future.channel().closeFuture().sync();
} finally {
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
}
}
第一部分
NIOEventLoop
属于Executor:查看源码发现,最终是实现Executor,一方面说明了Executor的实现类,可以是线程,可以是线程池,最终会调用execute方法来执行任务。
public interface Executor {
/**
* Executes the given command at some time in the future. The command
* may execute in a new thread, in a pooled thread, or in the calling
* thread, at the discretion of the {@code Executor} implementation.
*/
//此接口的实现类,会使用此方法执行一个将来某个时刻的命令,说明是异步执行。而这个命令可能在一个线程
//或者一个线程池,或者是调用此方法的线程执行,主要取决于,此接口的实现类
void execute(Runnable command);
}
内部封装了一个executor。本身是一个executor,为何内部又封装了一个,为何???**不过可以得知内部肯定有两个execute方法来执行各自的任务。**
NIOEventLoopGroup
属于Executor:那么意味着NIOEventLoopGroup也是一个执行器,可以用来执行任务,那么必然也存在execute方法,那么它的execute具体是干什么呢??
class AbstractEventExecutorGroup implements EventExecutorGroup{
@Override
public void execute(Runnable command) {
next().execute(command);
}
}
- 最终在父类中找到了,execute方法,那么next()是什么?next()获取到的就是EventLoop,因为EventLoop也是Executor,所以可以执行executor方法,那么NIOEventLoopGroup的execute就是,将在自己的池中选择一个EventLoop,然后将任务交给他来执行。
- 内部也封装了一个executor。本身是一个executor,为何内部又封装了一个,为何???不过可以得知内部肯定有两个execute方法来执行各自的任务。
第二部分
- 里面的代码主要是用于初始化channel
- 问题点:下面这些类到底如何使用
- attr和childAttr
- handler和child
- option和childOption