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);
        }
    }
相关推荐
c_zyer3 小时前
FreeSWITCH与Java交互实战:从EslEvent解析到Spring Boot生态整合的全指南
spring boot·netty·freeswitch·eslevent
Derek_Smart2 天前
工业物联网千万级设备通信优化:Netty多帧解码器实战,性能提升
java·性能优化·netty
皮皮林55117 天前
Netty 超详细解答十问十答
netty
idolyXyz24 天前
[netty5: LifecycleTracer & ResourceSupport]-源码分析
netty·netty-buffer
idolyXyz25 天前
[netty5: WebSocketServerHandshaker & WebSocketServerHandshakerFactory]-源码分析
netty
idolyXyz1 个月前
[netty5: WebSocketFrameEncoder & WebSocketFrameDecoder]-源码解析
netty
idolyXyz1 个月前
[netty5: HttpObjectEncoder & HttpObjectDecoder]-源码解析
netty
Derek_Smart1 个月前
基于Netty与Spring Integration的高并发工业物联网网关架构设计与实现
spring boot·物联网·netty
迢迢星万里灬1 个月前
Java求职者面试指南:微服务技术与源码原理深度解析
java·spring cloud·微服务·dubbo·netty·分布式系统·面试指南
Y_3_71 个月前
Netty实战:从核心组件到多协议实现(超详细注释,udp,tcp,websocket,http完整demo)
linux·运维·后端·ubuntu·netty