Netty — (二) 组件:EventLoop
EventLoop
EventLoop 本质是一个单线程执行器(同时维护了一个Selector),里面有run方法处理Channel上源源不断的IO事件
它的继承关系比较复杂:
- 一条线是继承自 java.util.concurrent.ScheduledExecutorService,因此包含了线程池中所有的方法
- 另一条线是继承自netty自己的 OrderedEventExecutor
- 提供了 boolean inEventLoop(Thread thread) 方法判断一个线程是否属于此 EventLooP
- 提供了 parent 方法来看看自己属于哪个 EventLoopGroup
EventLoopGroup 是一组 EventLoop,Channel 一般会调用 EventLoopGroup 的 register 方法来绑定其中一个 EventLoop,后续这个Channel 上的 IO 事件都由此 EventLoop 来处理(保证了 IO 事件处理时的线程安全)
- 继承自 netty 自己的 EventExecutorGroup
- 实现了 Iterable 接口提供遍历 EventLoop 的能力
- 另有 next 方法获取集合中下一个 EventLoop
@Log4j2
public class TestEventLoop {
public static void main(String[] args) {
// 创建事件循环组
EventLoopGroup group = new NioEventLoopGroup(2);// IO 事件,普通任务,定时任务
// EventLoopGroup group = new DefaultEventLoopGroup();// 普通任务,定时任务
System.out.println(group.next());
System.out.println(group.next());
System.out.println(group.next());
System.out.println(group.next());
// 执行普通任务
// group.next().submit(() -> {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// log.debug("ok");
// });
// 定时任务
group.next().scheduleAtFixedRate(() -> {
log.debug("ok");
}, 0, 1, TimeUnit.SECONDS);
log.debug("main");
}
}
handler 线程切换
static void invokeChannelRead(final AbstractChannelHandlerContext next, Object msg) {
final Object m = next.pipeline.touch(ObjectUtil.checkNotNull(msg, "msg"), next);
EventExecutor executor = next.executor(); // 返回下一个handler的EventLoop
// 是,直接调用
if (executor.inEventLoop()) {// 当前handler中的线程,是否和eventLoop是同一个线程
next.invokeChannelRead(m);
} else {// 不是,将要执行的代码作为任务提交个下一个事件循环处理(换人)
executor.execute(new Runnable() {// 下一个handler线程
public void run() {
next.invokeChannelRead(m);
}
});
}
}
/**
*如果两个handler绑定的是同一个线程,那么就直接调用,否则,把要调用的代码封装为一个任务对象,
*由下一个handler的线程来调用
*/
上述就是EventLoop 组件的讲解,包括一些案例的实现,继续关注,后续更精彩。