Netty中的ChannelHandler和ChannelHandlerContext

Netty 引入 ChannelHandlerContext 来封装 ChannelHandler 的原因,在代码设计上还是遵循单一职责的原则, ChannelHandler 是用户接触最频繁的一个 netty 组件,netty 希望用户能够把全部注意力放在最核心的 IO 处理上,用户只需要关心自己对哪些异步事件感兴趣并考虑相应的处理逻辑即可,而并不需要关心异步事件在 pipeline 中如何传递,如何选择具有执行条件的 ChannelHandler 去执行或者跳过。这些切面性质的逻辑,netty 将它们作为上下文信息全部封装在 ChannelHandlerContext 中由netty框架本身负责处理。

为什么要单独强调在 inbound 事件传播的过程中发生异常,才会回调 exceptionCaught 呢 ?

因为 inbound 事件一般都是由 netty 内核触发传播的,而 outbound 事件一般都是由用户选择触发的,比如用户在处理完业务逻辑触发的 write 事件或者 flush 事件。

而在用户触发 outbound 事件后,一般都会得到一个 ChannelPromise 。用户可以向 ChannelPromise 添加各种 listener 。当 outbound 事件在传播的过程中发生异常时,netty 会通知用户持有的这个 ChannelPromise ,但不会触发 exceptionCaught 的回调

而 outbound 事件中只有 flush 事件的传播是个例外,当 flush 事件在 pipeline 传播的过程中发生异常时,会触发对应异常 ChannelHandler 的 exceptionCaught 事件回调。因为 flush 方法的签名中不会给用户返回 ChannelPromise 。

java 复制代码
    //io.netty.channel.AbstractChannelHandlerContext#flush
    @Override
    public ChannelHandlerContext flush() {
        final AbstractChannelHandlerContext next = findContextOutbound(MASK_FLUSH);
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            next.invokeFlush();
        } else {
            Tasks tasks = next.invokeTasks;
            if (tasks == null) {
                next.invokeTasks = tasks = new Tasks(next);
            }
            safeExecute(executor, tasks.invokeFlushTask, channel().voidPromise(), null, false);
        }

        return this;
    }

    private void invokeFlush0() {
        try {
            ((ChannelOutboundHandler) handler()).flush(this);
        } catch (Throwable t) {
            invokeExceptionCaught(t);
        }
    }
相关推荐
ktkiko111 个月前
Netty中的NioEventloop(1)
java·开发语言·netty·高并发学习
董可伦1 个月前
Netty 入门学习
rpc·spark·netty·通信
相隔一个图书馆的距离1 个月前
netty系列(五)IdleStateHandler和IdleStateHandlerEventState
java·netty·idlehandler
诸葛小猿2 个月前
哪些框架、软件、中间件使用了netty? 哪些中间件、软件底层使用了epoll?
netty·epoll
power-辰南2 个月前
Netty 常见面试题原理解析
java·开发语言·netty·nio
drebander2 个月前
Netty 性能优化与调试指南
网络·性能优化·netty
JWASX2 个月前
定时/延时任务-Netty时间轮源码分析
java·netty·定时任务·时间轮
drebander2 个月前
Netty 的 SSL/TLS 安全通信
网络·netty·ssl
drebander2 个月前
使用 Netty 实现 RPC 通信框架
网络协议·rpc·netty
drebander2 个月前
使用 Netty 实现 WebSocket 通信
websocket·网络协议·netty