EventLoop

事件循环对象

本质是一个单线程执行器(同时维护了一个Selector),里面有run方法处理Channel上源源不断的io事件。

它的继承关系有:

  • java.util.concurrent.ScheduledExecutorService因此包含了线程池中所有的方法
  • io.netty.util.concurrent.OrderedEventExecutor,
    • 提供了boolean inEventLoop(Thread thread)方法判断一个线程是否属于此EventLoop
    • 提供了parent 方法来看看自己属于哪个EventLoopGroup
  • io.netty.util.concurrent.EventExecutorGroup,
    • 实现了Iterable接口提供遍历EventLoop的能力
    • 另有next方法获取集合中下一个EventLoop

Java EventLoop接口

其子类: Java EventLoop子类

EventLoopGroup

是一组EventLoop,Channel一般会调用EventLoopGroup的register方法来绑定其中一个EventLoop,后续这个Channel上的io事件都又此EventLoop来处理(保证了io事件处理时的线程安全)

  • 继承自netty自己的EventExecutorGroup

    • 实现了Iterable接口提供遍历EventLoop的能力
    • 另有next方法获取集合中下一个EventLoop
    // 内部创建了两个 EventLoop, 每个 EventLoop 维护一个线程
    DefaultEventLoopGroup group = new DefaultEventLoopGroup(2);
    System.out.println(group.next());
    System.out.println(group.next());
    System.out.println(group.next());
    //输出
    io.netty.channel.DefaultEventLoop@60f82f98
    io.netty.channel.DefaultEventLoop@35f983a6
    io.netty.channel.DefaultEventLoop@60f82f98

优雅关闭

shutdownGracefully()方法。该方法会首先切换EventLoopGroup到关闭状态从而拒绝新的任务加入,然后在任务队列都处理完成后,停止线程的运行。从而确保应用是在正常有序的状态下退出的。

NioEventLoop

可处理io事件、普通任务、定时任务

继承自io.netty.channel.MultithreadEventLoopGroup

演示处理普通任务和定时任务

package com.yakiniku.netty.c2;
import io.netty.channel.DefaultEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
/**
* @Author: yakiniku
* NioEventLoopGroup 可传入线程数量 如果不传入,默认为0,然后最终调用的方法是
*
* MultithreadEventLoopGroup 类下的
* protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
* super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
* }
*
* 而 DEFAULT_EVENT_LOOP_THREADS 来自:
* static {
* DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
* "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
*
* if (logger.isDebugEnabled()) {
* logger.debug("-Dio.netty.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS);
* }
* }
*
* 找到系统核心数再*2
*
* 启动时打印了
* [main] DEBUG io.netty.channel.MultithreadEventLoopGroup - -Dio.netty.eventLoopThreads: 16
*
*
*/
@Slf4j
public class TestEventLoop {
public static void main(String[] args) {
NioEventLoopGroup group = new NioEventLoopGroup(2); //处理io事件、普通任务、定时任务
// DefaultEventLoop group = new DefaultEventLoop(); // 处理普通任务、定时任务
System.out.println(group.next());
System.out.println(group.next());
System.out.println(group.next());
//执行普通任务
group.next().submit(()->{
log.debug("ok");
});
//执行定时任务
group.next().scheduleAtFixedRate(()->{
log.debug("定时任务---");
},0,2, TimeUnit.SECONDS);
log.debug("main");
group.shutdownGracefully();
}
}

演示处理io事件Server

package com.yakiniku.netty.c2;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.Charset;
/**
* @Author: yakiniku
*
*/
@Slf4j
public class EventLoopServer {
public static void main(String[] args) {
new ServerBootstrap()
.group(new NioEventLoopGroup(2))
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast("inbound-1",new ChannelInboundHandlerAdapter(){
@Override //ByteBuf
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
log.debug(byteBuf.toString(Charset.defaultCharset()));
super.channelRead(ctx, msg);
}
});
}
}).bind(9070);
}
}

演示处理io事件 Client

package com.yakiniku.netty.c2;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
/**
* @Author: yakiniku
*
*/
@Slf4j
public class EventLoopClient {
public static void main(String[] args) throws InterruptedException {
//1. 启动类
Channel channel = new Bootstrap()
//2。 添加EventLoop
.group(new NioEventLoopGroup())
//3. 连接客户端 channel实现
.channel(NioSocketChannel.class)
//4. 添加处理器
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override //连接建立后初始化操作
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
nioSocketChannel.pipeline().addLast(new StringEncoder());
}
})
//5. 连接到服务器
.connect(new InetSocketAddress("localhost", 9070))
.sync()
.channel();
log.debug(channel.toString());
// 在这里设置断点。
System.out.println();
}
}

注意设置IDEA设置断点类型要更改为Thread。ALL:阻塞所有线程;Thrad:阻塞当前线程。

NioEventLoopGroup里有两个EventLoop,不同Channel会和其中的EventLoop绑定

NioEventLoopGroup

EventLoop 分工细化

细分一 细分二

  • 细分一: 将处理accept事件和处理读写事件的EventLoop分开。分为boss、worker

不需要给第一个(parentGroup)NioEventLoopGroup设置线程数,因为ServerSocketChannel只有一个,也只会跟其中一个EventLoop绑定(服务器只有一个)

new ServerBootstrap()
.group(new NioEventLoopGroup(),new NioEventLoopGroup(2))
.channel(NioServerSocketChannel.class)
.....
group里可以传两个EventLoopGroup,我们传第一个,可以只负责ServerSocketChannel上的accept事件,
第二个只负责socketChannel上的读写
/**
* Set the EventLoopGroup for the parent (acceptor) and the child (client). These
* EventLoopGroup's are used to handle all the events and IO for ServerChannel and
* Channel's.
*/
public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) {
super.group(parentGroup);
if (this.childGroup != null) {
throw new IllegalStateException("childGroup set already");
}
this.childGroup = ObjectUtil.checkNotNull(childGroup, "childGroup");
return this;
}
  • 细分二: 进一步细分。如果一个channel上处理花费的时间比较长,会影响到其他的channel。

创建一个独立的EventLoopGroup

@Slf4j
public class EventLoopServer {
public static void main(String[] args) {
// 创建一个独立的 DefaultEventLoop
DefaultEventLoop defaultEventLoop = new DefaultEventLoop();
new ServerBootstrap()
// 细分1:
.group(new NioEventLoopGroup(),new NioEventLoopGroup(2))
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast("inboundHandler-1",new ChannelInboundHandlerAdapter(){
@Override //ByteBuf
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
log.debug(byteBuf.toString(Charset.defaultCharset()));
super.channelRead(ctx, msg);
}
//可以传入一个EventLoop 这个handler会交由该EventLoop处理
}).addLast(defaultEventLoop,"inboundHandler-2",new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
log.debug("handler-2");
super.channelRead(ctx, msg);
}
});
}
}).bind(9070);
}
}

NioEventloop

💡handler之间如何交换?

关键代码: io.netty.channel.AbstractChannelHandlerContext#invokeChannelRead()

ChannelInboundHandlerAdapter 里的父类方法

public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ctx.fireChannelRead(msg);
}

如果两个handler绑定的是同一个EventLoop(一个线程),就直接调用,否则就将要调用的代码封装为一个任务对象,由下一个handler的线程来调用

static void invokeChannelRead(finalAbstractChannelHandlerContext next, Object msg) {
finalObject m = next.pipeline.touch(ObjectUtil.checkNotNull(msg, "msg"), next);
//获取下一个handler执行器 EventLoop的另一个继承 EventExecutor
EventExecutor executor = next.executor();
//判断下一个handler的事件循环是否与当前的事件循环是同一个线程
if(executor.inEventLoop()) {
//直接调用
next.invokeChannelRead(m);
}else{
//将要执行的代码作为任务提交给下一个事件循环处理
executor.execute(new Runnable() {
@Override
public void run() {
next.invokeChannelRead(m);
}
});
}
}