Selector 事件选择器(多路复用器)
- 用于检查一个或多个NIO Channel(通道)的状态是否处于可读、可写。如此可以实现单线程管理多个channels,也就是可以管理多个网络链接
Provider模式
- 通常Provider由3个角色组成: 接口(协议)-提供者-实现者
- 分离实现者与应用者, 相互间使用统一协议(接口)进行交互
// EventLoopGroup传递SelectorProvider提供者给EventLoop
public class NioEventLoopGroup implements EventExecutorGroup {
...
public NioEventLoopGroup(int nThreads) {
// SelectorProvider提供者
this(nThreads, SelectorProvider.provider());
}
public NioEventLoopGroup(int nThreads, final SelectorProvider selectorProvider) {
this(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, selectorProvider, DefaultEventExecutorChooserFactory.INSTANCE);
}
}
代码语言:javascript复制// selector的实现: provider.openSelector() 通过提供者返回适配的selector实现
public class NioEventLoop extends SingleThreadEventLoop {
private Selector selector;
private final SelectorProvider provider;
public NioEventLoop(SelectorProvider selectorProvider) {
this.provider = selectorProvider;
this.selector = openSelector();
}
private Selector openSelector() {
try {
return provider.openSelector();
} catch (IOException e) {
throw new ChannelException("failed to open a new selector", e);
}
}
}
https://github.com/spbreak/i-netty/tree/master/03-selector