程序员

netty源码分析(1)-Channel创建过程

2019-02-18  本文已影响0人  Jorgezhong
ChannelFuture future = serverBootstrap.bind(PORT).sync();
ChannelFuture future = bootstrap.connect(HOST, PORT).sync();

调用链如下:


最终是调用ChannelFatorynewChannel()方法。

  1. 查看AbstractBootstrap.initAndRegister()以下代码
channel = channelFactory.newChannel();

channel是由AbstarctBootstrap的成员变量channelFactory进行实例化的。

private volatile ChannelFactory<? extends C> channelFactory;
  1. 查看AbstractBootstrap初始化channelFactory的过程
 serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new DataServerInitializer());

在引导的时候调用了channel()方法配置了具体的Channel的class对象,进入channel()查看

public B channel(Class<? extends C> channelClass) {
        if (channelClass == null) {
            throw new NullPointerException("channelClass");
        }
        //配置ChannelFactory
        return channelFactory(new ReflectiveChannelFactory<C>(channelClass));
    }

进入channelFactory()方法,发现改方法仅仅将参数传递进入并并初始化AbstractBootstrap的成员变量

    public B channelFactory(ChannelFactory<? extends C> channelFactory) {
        if (channelFactory == null) {
            throw new NullPointerException("channelFactory");
        }
        if (this.channelFactory != null) {
            throw new IllegalStateException("channelFactory set already");
        }
        //初始化成员变量
        this.channelFactory = channelFactory;
        return (B) this;
    }

关键是new ReflectiveChannelFactory<C>(channelClass)干了什么

public class ReflectiveChannelFactory<T extends Channel> implements ChannelFactory<T> {

    private final Class<? extends T> clazz;

    public ReflectiveChannelFactory(Class<? extends T> clazz) {
        if (clazz == null) {
            throw new NullPointerException("clazz");
        }
        this.clazz = clazz;
    }

    @Override
    public T newChannel() {
        try {
            return clazz.newInstance();
        } catch (Throwable t) {
            throw new ChannelException("Unable to create Channel from class " + clazz, t);
        }
    }

    @Override
    public String toString() {
        return StringUtil.simpleClassName(clazz) + ".class";
    }
}

ReflectiveChannelFactory持有了一个Class<? extends T> clazz 并在实例化该对象的时候初始化该成员变量,实现了ChannelFactory接口,并实现了newChannel()方法,该方法直接调用clazz.newInstance()进行实例化。也就是最初配置的具体的ChannelNioServerSocketChannel.class

serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new DataServerInitializer());
  1. 回过头来查看initAndRegister()方法中,调用的newChannel()其实就是ChanelFactory接口定义的。由具体的Factory实现
channel = channelFactory.newChannel();
@Deprecated
public interface ChannelFactory<T extends Channel> {
    /**
     * Creates a new channel.
     */
    T newChannel();
}
上一篇下一篇

猜你喜欢

热点阅读