Netty组件EventLoop、EventLoopGroup
1 EventLoop
事件循环
EventLoop->EventLoopGroup->EventExecutorGroup->ScheduledExecutorService, Iterable
EventLoop->OrderedEventExecutor->EventExecutor->EventExecutorGroup
2 EventLoopGroup
事件循环组
NioEventLoopGroup 处理IO事件和普通事件、定时任务
DefaultEventLoopGroup 普通事件、定时任务
new NioEventLoopGroup() 构造方法可以指定线程,默认是电脑核数*2
3 代码
EventLoopGroup loopGroup = new NioEventLoopGroup(2);
// System.out.println(NettyRuntime.availableProcessors() * 2);
//2 获取下个事件对象 因为只有2个线程,
System.out.println(loopGroup.next());
System.out.println(loopGroup.next());
System.out.println(loopGroup.next());
System.out.println(loopGroup.next());
//输出结果
// io.netty.channel.nio.NioEventLoop@783e6358
// io.netty.channel.nio.NioEventLoop@17550481
// io.netty.channel.nio.NioEventLoop@783e6358
// io.netty.channel.nio.NioEventLoop@17550481
//3 普通任务
loopGroup.next().submit(()->{
System.out.println("2");
});
//定时任务
loopGroup.next().scheduleAtFixedRate(()->{
System.out.println("111");
},1,1, TimeUnit.SECONDS);
EventLoop分工细化
EventLoopGroup boss = new NioEventLoopGroup(); //只负责accept事件 不需要设置成1 new NioEventLoopGroup(1) 因为NioServerSocketChannel只会与1个boss绑定,注册,所以不需要设置成1
EventLoopGroup work = new NioEventLoopGroup(); //负责读写操作 此处不设置,会根据cpu核数 cpu*2
new ServerBootstrap().group(boss, work)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf bb = (ByteBuf) msg;
log.debug(bb.toString(Charset.defaultCharset()));
}
});
}
}).bind(8000);
继续细化
//细分2 创建一个独立EventLoopGroup
EventLoopGroup group = new DefaultEventLoop();
EventLoopGroup boss = new NioEventLoopGroup(); //只负责accept事件 不需要设置成1 new NioEventLoopGroup(1) 因为NioServerSocketChannel只会与1个boss绑定,注册,所以不需要设置成1
EventLoopGroup work = new NioEventLoopGroup(); //负责读写操作 此处不设置,会根据cpu核数 cpu*2
new ServerBootstrap().group(boss, work)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ch.pipeline().addLast("handler1", new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf bb = (ByteBuf) msg;
log.debug(bb.toString(Charset.defaultCharset()));
ctx.fireChannelRead(msg);
}
}).addLast(group, "handler2", new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf bb = (ByteBuf) msg;
log.debug(bb.toString(Charset.defaultCharset()));
}
});
}
}).bind(8000);
//多路服用 1个work线程管理多channel