netty线程模型、源码解析

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视图

  1. EventExecutorGroup里面有一个EventExecutor数组,保存了多个EventExecutor;

  2. EventExecutorGroup是不干事情,当收到一个请后,他就调用next()获得一个它里面的EventExecutor,再调用这个executor的方法;

  3. next(): EventExecutorChooser.next()定义选择EventExecutor的策略;

执行的流程

首先加载进来ServerBootstrap —> group 中 BossEventLoopGroup —> childGroup 中 WorkerEventLoopGroup —> channel 中 NioServerSocketChannel —> handlerz 中 加到NioServerSocketChannel Pipeline的handler —> childHander 中 加到NioSocketChannel accept()返回的)Pipeline的handler

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值