Reactor模式
Douglas C. Schmidt 1995年提出
An Object Behavioral Pattern for Demultiplexing and Dispatching Handles for Synchronous Events
Scalable IO in Java - Doug Lea
http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf
基于Java IO对Reactor模式进行阐述
NIO网络框架的典型模式
Mina、Netty、Cindy都是此模式的实现
Douglas
Doug Lea三种模式
单线程Reactor
多个客户端同时请求过来,接收到信息
多线程Reactor
当单个线程无法使用的时候, 那就用多个线程同时来处理,接收和处理请求
Multiple Reactor
当多个线程也不够的时候,那就启用多个reactor进行分工处理
其他形式 - 主从Reactor 不常用
Netty和Reactor的模式同时都支持的
单线程的Reactor
EventLoopGroup eventExecutors = new NioEventLoopGroup(1);
ServerBootstrap serverBootstrap = new ServerBootstrap().group(eventExecutors,eventExecutors);
多线程
默认不加参数的话,启动线程数是当前核线程数的两倍
EventLoopGroup eventExecutors = new NioEventLoopGroup(1);
ServerBootstrap serverBootstrap = new ServerBootstrap().group(eventExecutors,eventExecutors);//Handler使用线程池进行处理
Multiple Reactor
EventLoopGroup eventExecutors = new NioEventLoopGroup(1);
EventLoopGroup workereventExecutors = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap().group(eventExecutors,workereventExecutors);
EventLoopGroup eventExecutors = new NioEventLoopGroup();
EventLoopGroup workereventExecutors = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap().group(eventExecutors,workereventExecutors);
Multiple Reactor 所有线程都在线程中完成,不单独启动线程
源码解析
EventExecutor视图
-
EventExecutorGroup里面有一个EventExecutor数组,保存了多个EventExecutor;
-
EventExecutorGroup是不干事情,当收到一个请后,他就调用next()获得一个它里面的EventExecutor,再调用这个executor的方法;
-
next(): EventExecutorChooser.next()定义选择EventExecutor的策略;
执行的流程
首先加载进来ServerBootstrap —> group 中 BossEventLoopGroup —> childGroup 中 WorkerEventLoopGroup —> channel 中 NioServerSocketChannel —> handlerz 中 加到NioServerSocketChannel Pipeline的handler —> childHander 中 加到NioSocketChannel accept()返回的)Pipeline的handler