您当前的位置: 首页 > 

恐龙弟旺仔

暂无认证

  • 0浏览

    0关注

    282博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Netty源码解析- ChannelHandler相关实现类

恐龙弟旺仔 发布时间:2021-12-21 20:28:27 ,浏览量:0

前言:

    ChannelHandler我们之前有介绍过其接口作用,inbound和outbound事件的真正处理着就是ChannelHandler相关实现类。

    当我们使用Netty进行业务开发时,可以通过对ChannelHandler的实现类来进行业务处理。

    当然,我们还有其他更好的选择,Netty为我们提供了一些关于Netty的抽象类和实现类,我们可以选择直接继承。下面我们就来了解下ChannelHandler的相关实现类(抽象类)。

1.ChannelHandler部分实现类结构图

我们从上至下的来分析下各个类的作用及适用场景

2.ChannelHandler
public interface ChannelHandler {
    // ChannelHandler被添加后调用
    // ChannelPipeline.addFirst()方法添加ChannelHandlerContext后,会调用callHandlerAdded0方法
    void handlerAdded(ChannelHandlerContext ctx) throws Exception;
    
    // ChannelHandler被删除后调用
    // ChannelPipeline.remove()方法删除ChannelHandlerContext后,会调用callHandlerRemoved0
    void handlerRemoved(ChannelHandlerContext ctx) throws Exception;
    
    // 抛出异常时调用
    // 这个比较好玩,后续单独介绍
    void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception;
}

ChannelHandler接口给出的方法比较简单,基本看不出有inbound和outbound事件的痕迹。所以我们不直接使用这个接口,而是使用下面的接口。

3.ChannelInboundHandler接口

 之前有提到过这个接口,可以看到,这个接口所提供的的方法都是inbound入站事件所需要的,比如当客户端连接注册到EventLoop需要的channelRegistered注册事件、完成连接时的channelActive事件、客户端有信息传递过来时,服务端需要执行的channelRead事件等。

4.ChannelOutboundHandler

同样,作为outbound出站接口,其提供的都是出站事件。

客户端连接到远端server时的connect方法、写出信息到远端时的write方法。

Q:有一点不太明白的就是为何把read()也作为outbound里的方法?

精进版(Adapter):

    我们在实现上述inbound和outbound的相关ChannelHandler时,经常性的只关注某几个具体方法,其他的则会忽略。但是当我们直接实现ChannelOutboundHandler、ChannelInboundHandler接口时,则必须要实现其所有接口,对用户而言是一件非常冗余的事情,所以为了解决这个问题,Netty提供了Adapter相关抽象类,默认实现一些方法。

5.ChannelHandlerAdapter

public abstract class ChannelHandlerAdapter implements ChannelHandler {
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // NOOP
    }
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // NOOP
    }
    
    @Skip
    @Override
    @Deprecated
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.fireExceptionCaught(cause);
    }
    public boolean isSharable() {
        /**
         * Cache the result of {@link Sharable} annotation detection to workaround a condition. We use a
         * {@link ThreadLocal} and {@link WeakHashMap} to eliminate the volatile write/reads. Using different
         * {@link WeakHashMap} instances per {@link Thread} is good enough for us and the number of
         * {@link Thread}s are quite limited anyway.
         *
         * See #2289.
         */
        Class clazz = getClass();
        Map            
关注
打赏
1655041699
查看更多评论
0.0412s