netty 是事件驱动的,这里面有两个含义,一是 netty 接收到 socket 数据后,会产生事件,事件在 pipeline 上传播,二是事件由特定的线程池处理。

NioEventLoop 轮询网络事件

// io.netty.channel.nio.NioEventLoop#processSelectedKey
private void processSelectedKey(SelectionKey k, AbstractNioChannel ch) {
final AbstractNioChannel.NioUnsafe unsafe = ch.unsafe();
if (!k.isValid()) {
final EventLoop eventLoop;
try {
eventLoop = ch.eventLoop();
} catch (Throwable ignored) {
// If the channel implementation throws an exception because there is no event loop, we ignore this
// because we are only trying to determine if ch is registered to this event loop and thus has authority
// to close ch.
return;
}
// Only close ch if ch is still registered to this EventLoop. ch could have deregistered from the event loop
// and thus the SelectionKey could be cancelled as part of the deregistration process, but the channel is
// still healthy and should not be closed.
// See https://github.com/netty/netty/issues/5125
if (eventLoop == this) {
// close the channel if the key is not valid anymore
unsafe.close(unsafe.voidPromise());
}
return;
} try {
int readyOps = k.readyOps();
// We first need to call finishConnect() before try to trigger a read(...) or write(...) as otherwise
// the NIO JDK channel implementation may throw a NotYetConnectedException.
if ((readyOps & SelectionKey.OP_CONNECT) != 0) {
// remove OP_CONNECT as otherwise Selector.select(..) will always return without blocking
// See https://github.com/netty/netty/issues/924
int ops = k.interestOps();
ops &= ~SelectionKey.OP_CONNECT;
k.interestOps(ops); // 建立连接,深层会调用 fireChannelActive
unsafe.finishConnect();
} // Process OP_WRITE first as we may be able to write some queued buffers and so free memory.
if ((readyOps & SelectionKey.OP_WRITE) != 0) {
// Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write
ch.unsafe().forceFlush();
} // Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead
// to a spin loop
if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {
// 读数据,在流水线上传播读事件和连接关闭事件
unsafe.read();
}
} catch (CancelledKeyException ignored) {
unsafe.close(unsafe.voidPromise());
}
} // io.netty.channel.nio.AbstractNioByteChannel.NioByteUnsafe#read
public final void read() {
final ChannelConfig config = config();
if (shouldBreakReadReady(config)) {
clearReadPending();
return;
}
final ChannelPipeline pipeline = pipeline();
final ByteBufAllocator allocator = config.getAllocator();
final RecvByteBufAllocator.Handle allocHandle = recvBufAllocHandle();
allocHandle.reset(config); ByteBuf byteBuf = null;
boolean close = false;
try {
do {
byteBuf = allocHandle.allocate(allocator);
allocHandle.lastBytesRead(doReadBytes(byteBuf));
if (allocHandle.lastBytesRead() <= 0) {
// nothing was read. release the buffer.
byteBuf.release();
byteBuf = null;
close = allocHandle.lastBytesRead() < 0;
if (close) {
// There is nothing left to read as we received an EOF.
readPending = false;
}
break;
} allocHandle.incMessagesRead(1);
readPending = false;
// 触发 ChannelRead
pipeline.fireChannelRead(byteBuf);
byteBuf = null;
} while (allocHandle.continueReading()); allocHandle.readComplete();
// 触发 ChannelReadComplete
pipeline.fireChannelReadComplete(); if (close) {
// 触发 ChannelInactive 和 ChannelUnregister
closeOnRead(pipeline);
}
} catch (Throwable t) {
handleReadException(pipeline, byteBuf, t, close, allocHandle);
} finally {
// Check if there is a readPending which was not processed yet.
// This could be for two reasons:
// * The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method
// * The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method
//
// See https://github.com/netty/netty/issues/2254
if (!readPending && !config.isAutoRead()) {
removeReadOp();
}
}
}

HandlerContext 中有一个整数 executionMask,不同的 bit 位表示不同的事件,为 1 表示可以处理该事件。

// io.netty.channel.AbstractChannelHandlerContext
private final int executionMask; final class ChannelHandlerMask {
// Using to mask which methods must be called for a ChannelHandler.
static final int MASK_EXCEPTION_CAUGHT = 1;
static final int MASK_CHANNEL_REGISTERED = 1 << 1;
static final int MASK_CHANNEL_UNREGISTERED = 1 << 2;
static final int MASK_CHANNEL_ACTIVE = 1 << 3;
static final int MASK_CHANNEL_INACTIVE = 1 << 4;
static final int MASK_CHANNEL_READ = 1 << 5;
static final int MASK_CHANNEL_READ_COMPLETE = 1 << 6;
static final int MASK_USER_EVENT_TRIGGERED = 1 << 7;
static final int MASK_CHANNEL_WRITABILITY_CHANGED = 1 << 8;
static final int MASK_BIND = 1 << 9;
static final int MASK_CONNECT = 1 << 10;
static final int MASK_DISCONNECT = 1 << 11;
static final int MASK_CLOSE = 1 << 12;
static final int MASK_DEREGISTER = 1 << 13;
static final int MASK_READ = 1 << 14;
static final int MASK_WRITE = 1 << 15;
static final int MASK_FLUSH = 1 << 16; private static final int MASK_ALL_INBOUND = MASK_EXCEPTION_CAUGHT | MASK_CHANNEL_REGISTERED |
MASK_CHANNEL_UNREGISTERED | MASK_CHANNEL_ACTIVE | MASK_CHANNEL_INACTIVE | MASK_CHANNEL_READ |
MASK_CHANNEL_READ_COMPLETE | MASK_USER_EVENT_TRIGGERED | MASK_CHANNEL_WRITABILITY_CHANGED;
private static final int MASK_ALL_OUTBOUND = MASK_EXCEPTION_CAUGHT | MASK_BIND | MASK_CONNECT | MASK_DISCONNECT |
MASK_CLOSE | MASK_DEREGISTER | MASK_READ | MASK_WRITE | MASK_FLUSH;
}

以 ChannelActive 为例,通过比较 bit 位上的值,判断该 HandlerContext 是否处理 ChannelActive 事件

// io.netty.channel.AbstractChannelHandlerContext#fireChannelActive
public ChannelHandlerContext fireChannelActive() {
invokeChannelActive(findContextInbound(MASK_CHANNEL_ACTIVE));
return this;
} // io.netty.channel.AbstractChannelHandlerContext#findContextInbound
private AbstractChannelHandlerContext findContextInbound(int mask) {
AbstractChannelHandlerContext ctx = this;
do {
ctx = ctx.next;
} while ((ctx.executionMask & mask) == 0);
return ctx;
}

如何使用 UserEvent?

首先让自己的 handler 实现 userEventTriggered 方法

class MyInboundHandler extends SimpleChannelInboundHandler<Object> {

    @Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
// 处理事件,简单打印
System.out.println(evt);
// 从当前 HandlerContext 向后传播 evt,如果没有这行代码,则不会向后传播事件了
super.userEventTriggered(ctx, evt);
} @Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
super.channelRead0(ctx, msg);
}
}

通过 pipeline 传播事件,从 HeadContext 向后传播事件

channel.pipeline().fireUserEventTriggered("i am an event");

read 事件,是从 HeadContext 开始向后传播

write 操作,是从 TailContext 开始向前传播

netty 的事件驱动的更多相关文章

  1. Netty http client 编写总结

    Apache http client 有两个问题,第一个是 apache http client 是阻塞式的读取 Http request, 异步读写网络数据性能更好些.第二个是当 client 到 ...

  2. Netty那点事

    一.Netty是什么 Netty,无论新手还是老手,都知道它是一个“网络通讯框架”. 所谓框架,基本上都是一个作用:基于底层API,提供更便捷的编程模型. 那么”通讯框架”到底做了什么事情呢?回答这个 ...

  3. 【转】Netty那点事(一)概述

    [原文https://github.com/code4craft/netty-learning/blob/master/posts/ch1-overview.md#%E5%90%88%E5%BC%80 ...

  4. Netty那点事: 概述, Netty中的buffer, Channel与Pipeline

    Netty那点事(一)概述 Netty和Mina是Java世界非常知名的通讯框架.它们都出自同一个作者,Mina诞生略早,属于Apache基金会,而Netty开始在Jboss名下,后来出来自立门户ne ...

  5. 微服务框架概览之 Netty

    Netty 是什么 Netty 提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高可靠性的网络服务器和客户端程序 Netty 架构图 为什么选择Netty 通过对Netty的分析,我 ...

  6. Netty浅析

    Netty是JBoss出品的高效的Java NIO开发框架,关于其使用,可参考我的另一篇文章 netty使用初步.本文将主要分析Netty实现方面的东西,由于精力有限,本人并没有对其源码做了极细致的研 ...

  7. Netty中的三种Reactor(反应堆)

    目录: Reactor(反应堆)和Proactor(前摄器) <I/O模型之三:两种高性能 I/O 设计模式 Reactor 和 Proactor> <[转]第8章 前摄器(Proa ...

  8. Netty 源码 NioEventLoop(一)初始化

    Netty 源码 NioEventLoop(一)初始化 Netty 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html) Netty 基于事件 ...

  9. Netty框架入门

    一.概述     Netty是由JBOSS提供的一个java开源框架.     Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高可靠性的网络服务器和客户端程序.   二. ...

随机推荐

  1. 时序数据库 Apache-IoTDB 源码解析之文件数据块(四)

    上一章聊到行式存储.列式存储的基本概念,并介绍了 TsFile 是如何存储数据以及基本概念.详情请见: 时序数据库 Apache-IoTDB 源码解析之文件格式简介(三) 打一波广告,欢迎大家访问Io ...

  2. [python]bytes和str

    Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] ...

  3. Codeforces_442_A_枚举

    http://codeforces.com/problemset/problem/442/A 想想成5*5的图,一共能划10条线,枚举2^10次即可. 判断每种情况是否符合条件的方法,若存在点,被线穿 ...

  4. Java程序员必备英文单词

    列表中共有769个单词,这些单词是从JDK.Spring.SpringBoot.Mybatis的源码中解析得到,按照在源码中出现的频次依次排列,页面中的单词是出现频次大于1000的.单词的音标.翻译结 ...

  5. CyclicBarrier与CountDownLatch区别

    阻塞与唤醒方式的区别 CountDownLatch计数方式 CountDownLatch是减计数.调用await()后线程阻塞.调用countDown()方法后计数减一,当计数为零时,调用await( ...

  6. 阿里云服务器ECS Ubuntu18.04 初次使用配置教程(图形界面安装)

    最近由于工作需要,要使用服务器测试,就先自已买了个服务器,就在阿里云买了一个,先买了那个叫虚拟主机的,后来发现不是我需要的,所以退了,就先了这个ECS主机.3年.如果购买就上图了.下面直接进入正题. ...

  7. 《自拍教程16》cmd的常用技巧

    cmd.exe是Windows 自带的命令行操作交互界面软件. 虽然功能有限,但是毕竟是默认的命令行操作交互界面软件. 肯定所有的电脑都是自带的. 当然现在已经有很多改良版的,交互体验更好的cmd类似 ...

  8. Java也疯狂-分享利用ffmpeg做视频转换的工具

    朋友需要经常将视频统一转换为mp4格式,市面上的工具很多,但是转换的体积.自动化程度等都不好,于是花了一个小时给朋友写了个给予ffmpeg的批量转换工具,功能简单但是很实用,也正好给学习Java的同学 ...

  9. PYTHON 学习笔记4 模块的使用、基本IO 写入读取、JSON序列化

    前言 若在之前写代码的方式中,从Python 解释器进入.退出后再次进入,其定义的变量.函数等都会丢失.为了解决这个为,我们需要将需要的函数.以及定义的变量等都写入一个文件当中.这个文件就叫做脚本 随 ...

  10. 404 not found Webshell

    404 not found Webshell 克隆或下载项目: git clone https://github.com/CosasDePuma/SecurityNotFound.git Securi ...