netty源码分析(1)-Channel创建过程
2019-02-18 本文已影响0人
Jorgezhong
- 初始化入口:bind()/connect()方法
ChannelFuture future = serverBootstrap.bind(PORT).sync();
ChannelFuture future = bootstrap.connect(HOST, PORT).sync();
调用链如下:
最终是调用ChannelFatory
的newChannel()
方法。
- 实例化Channel
- 查看
AbstractBootstrap.initAndRegister()
以下代码
channel = channelFactory.newChannel();
channel是由AbstarctBootstrap
的成员变量channelFactory
进行实例化的。
private volatile ChannelFactory<? extends C> channelFactory;
- 查看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());
- 回过头来查看
initAndRegister()
方法中,调用的newChannel()
其实就是ChanelFactory
接口定义的。由具体的Factory实现
channel = channelFactory.newChannel();
@Deprecated
public interface ChannelFactory<T extends Channel> {
/**
* Creates a new channel.
*/
T newChannel();
}