服务器启动代码

  1. public class SomeServer {
  2. public static void main(String[] args) throws InterruptedException {
  3. //第一部分
  4. EventLoopGroup parentGroup = new NioEventLoopGroup();
  5. EventLoopGroup childGroup = new NioEventLoopGroup();
  6. try {
  7. //第二部分
  8. ServerBootstrap bootstrap = new ServerBootstrap();
  9. // 将parentGroup、childGroup初始化到bootstrap
  10. bootstrap.group(parentGroup, childGroup)
  11. // 将指定类型的channel的工厂类初始化到bootstrap
  12. .channel(NioServerSocketChannel.class)
  13. .attr(AttributeKey.valueOf("depart"), "行政部")
  14. .childAttr(AttributeKey.valueOf("addr"), "北京海淀")
  15. // 添加日志处理器
  16. .handler(new LoggingHandler(LogLevel.INFO))
  17. .childHandler(new ChannelInitializer<SocketChannel>() {
  18. @Override
  19. protected void initChannel(SocketChannel ch) throws Exception {
  20. ChannelPipeline pipeline = ch.pipeline();
  21. pipeline.addLast(new StringDecoder());
  22. }
  23. });
  24. //第三部分
  25. ChannelFuture future = bootstrap.bind(8888).sync();
  26. System.out.println("服务器已启动。。。");
  27. future.channel().closeFuture().sync();
  28. } finally {
  29. parentGroup.shutdownGracefully();
  30. childGroup.shutdownGracefully();
  31. }
  32. }
  33. }

第一部分

NIOEventLoop

  • 属于Executor:查看源码发现,最终是实现Executor,一方面说明了Executor的实现类,可以是线程,可以是线程池,最终会调用execute方法来执行任务。

    1. public interface Executor {
    2. /**
    3. * Executes the given command at some time in the future. The command
    4. * may execute in a new thread, in a pooled thread, or in the calling
    5. * thread, at the discretion of the {@code Executor} implementation.
    6. */
    7. //此接口的实现类,会使用此方法执行一个将来某个时刻的命令,说明是异步执行。而这个命令可能在一个线程
    8. //或者一个线程池,或者是调用此方法的线程执行,主要取决于,此接口的实现类
    9. void execute(Runnable command);
    10. }
  • 内部封装了一个executor。本身是一个executor,为何内部又封装了一个,为何???**不过可以得知内部肯定有两个execute方法来执行各自的任务。**

NIOEventLoopGroup

  • 属于Executor:那么意味着NIOEventLoopGroup也是一个执行器,可以用来执行任务,那么必然也存在execute方法,那么它的execute具体是干什么呢??

    1. class AbstractEventExecutorGroup implements EventExecutorGroup{
    2. @Override
    3. public void execute(Runnable command) {
    4. next().execute(command);
    5. }
    6. }
    • 最终在父类中找到了,execute方法,那么next()是什么?next()获取到的就是EventLoop,因为EventLoop也是Executor,所以可以执行executor方法,那么NIOEventLoopGroup的execute就是,将在自己的池中选择一个EventLoop,然后将任务交给他来执行。
  • 内部也封装了一个executor。本身是一个executor,为何内部又封装了一个,为何???不过可以得知内部肯定有两个execute方法来执行各自的任务。

**

第二部分

  • 里面的代码主要是用于初始化channel
  • 问题点:下面这些类到底如何使用
    • attr和childAttr
    • handler和child
    • option和childOption