addLast方法指定EventExecutorGroup

问题及代码示例:

客户端发送消息给服务端。服务端处理时,用的addLast()指定了DefaultEventLoopGroup多线程去执行serverhandler。然后定时去打印此handler的QPS。
预期和结果不符合。QPS打印是个位数。
用visualVM 查看服务端线程:发现DefaultEventLoopGroup就只有一个线程运行。
在这里插入图片描述

public class MyServer {
    public static void main(String[] args) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        DefaultEventLoopGroup eventLoopGroup = new DefaultEventLoopGroup(100);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(eventLoopGroup, new ServerHandler());
                        }
                    });
            //绑定端口号,启动服务端
            ChannelFuture channelFuture = bootstrap.bind(6666).sync();
            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
class ServerHandler extends ChannelInboundHandlerAdapter {
    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    AtomicInteger integer = new AtomicInteger(0);
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            int andSet = integer.get();
            System.out.println("SERVER HANDLER QPS IS :" + andSet);
        }, 0,1000, TimeUnit.MILLISECONDS);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            System.out.println("server handler start to process");
            // 模拟业务运行时间
            Thread.sleep(2000);
            integer.getAndAdd(1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ((ByteBuf)msg).release();
        }
    }
}

public class MyClient {
    public static void main(String[] args) throws Exception {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventExecutors)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //添加客户端通道的处理器
                            ch.pipeline().addLast(new ClientSendHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6666).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            eventExecutors.shutdownGracefully();
        }
    }
}
class ClientSendHandler extends ChannelInboundHandlerAdapter {
    ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        executorService.scheduleAtFixedRate(() -> {
            for (int i = 0; i < 100; i++) {
                try {
                    ByteBuf buffer = ctx.alloc().buffer(20);
                    // 模拟业务操作
                    Thread.sleep(new Random().nextInt(1000));
                    // 数据发送
                    buffer.writeBytes("hello, i am client".getBytes());
                    ctx.writeAndFlush(buffer);
                    System.out.println("client send success" + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },0, 1000, TimeUnit.MILLISECONDS);
    }
}

分析

进入addlast方法:
找到 newCtx = newContext(group, filterName(name, handler), handler);
其里面childExecutor(group)就是绑定的处理逻辑。可以看到就是从group里面取出的一个线程,然后将其与context绑定。而context包含handler,其实就是与handler绑定。后续的该handler的执行,都是用的同一个线程。
所以用该方法控制多线程执行handler根本上就是错误的。

    private EventExecutor childExecutor(EventExecutorGroup group) {
   		...
   		// SINGLE_EVENTEXECUTOR_PER_GROUP,与本次无关。下文有介绍
        Boolean pinEventExecutor = channel.config().getOption(ChannelOption.SINGLE_EVENTEXECUTOR_PER_GROUP);
        if (pinEventExecutor != null && !pinEventExecutor) {
            return group.next();
        }
		...
        EventExecutor childExecutor = childExecutors.get(group);
        if (childExecutor == null) {
            childExecutor = group.next();
            childExecutors.put(group, childExecutor);
        }
        return childExecutor;
    }

解决

  1. 服务器端自定义线程池执行业务逻辑
class ServerHandler extends ChannelInboundHandlerAdapter {
    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
    AtomicInteger integer = new AtomicInteger(0);
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(100);
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            int andSet = integer.get();
            System.out.println("SERVER HANDLER QPS IS :" + andSet);
        }, 0,1000, TimeUnit.MILLISECONDS);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        fixedThreadPool.submit(() -> {
            try {
                System.out.println("server handler start to process");
                // 模拟业务运行时间
                Thread.sleep(2000);
                integer.getAndAdd(1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                ((ByteBuf)msg).release();
            }
        });
    }

下图的poo1-2-thread-x就是执行的线程
在这里插入图片描述

  1. 客户端建立多次连接
    一个TPC连接对应一个socket、一个channel、一个pipeline。
    之前代码是一个客户端1s发100次,可以让客户端连服务端100次,每个TCP连接1s只发一个,貌似也达到了之前的效果。netty线程池

SINGLE_EVENTEXECUTOR_PER_GROUP 参数

每一个 channel 都会对应一个独立的 pipeline。该参数默认为true, 表示在一个 channel 对应的 pipeline 中,如果我们为多个 ChannelHandler 指定了同一个 EventExecutorGroup ,那么这多个 channelHandler 只能绑定到 EventExecutorGroup 中的同一个 EventExecutor 上。

总结

 ChannelPipeline addLast(EventExecutorGroup group, ChannelHandler... handlers);

group不是 为每个handler分配一个新的线程去执行。
而是对pipeline来讲的。

  1. 假设SINGLE_EVENTEXECUTOR_PER_GROUP为true,
    有A和B 两个pipeline,那么调用该方法后,A中的每个handler,都是同一个线程thread1去执行的。B中的每个handler都是由thread2去执行的
  2. SINGLE_EVENTEXECUTOR_PER_GROUP 为false,
    有A和B 两个pipeline,那么调用该方法后,A中的每个handler,都是不同的线程去执行,thread1、thread2。B中的每个handler也是由不同的线程thread3、thread4执行的。
    注意,这里只是举个例子,执行的线程到底是不是同一个,还要看group.next()逻辑。

参考:netty进阶之路-李林峰

作者:WKP9418
原文地址:https://blog.csdn.net/qq_43179428/article/details/140561346

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值