netty 4-1 如果服务端需要长时间的处理。我们可以通过queue处理

只需要修改handler中的read方法 前两行注释的是第一种情况,这中会阻塞。代码中是会开启一个新的线程执行,taskQueue 中会有两条数据。这两个是在一个线程中的要顺序执行 一共三十秒

  @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //比如这里我们有一个非常费时的操作。将其弄到NioEventLoop中的queue中就可以了
//        Thread.sleep(10*1000);
//        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端  这个是channelRead 方法", CharsetUtil.UTF_8));
ctx.channel().eventLoop().execute(()-> {//eventLoop这个是一个线程在执行,如果是多个任务,会把任务放在queue中
    try {
        Thread.sleep(10*1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端  这个是channelRead 方法", CharsetUtil.UTF_8));
});

        ctx.channel().eventLoop().execute(()-> {//eventLoop这个是一个线程在执行,如果是多个任务,会把任务放在queue中
            try {
                Thread.sleep(20*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端  这个是channelRead 方法2", CharsetUtil.UTF_8));
        });

//        System.out.println("服务器端:Thread.currentThread().getName() = " + Thread.currentThread().getName());
//        //这个方法是干嘛的呢。有上下文对象,我们可以拿到很多东西,还有msg
//        System.out.println("ctx = " + ctx);
//        //就像我们之前用ByteBuffer 一样。我们需要将数据封装到缓冲对象
//        ByteBuf byteBuf = (ByteBuf) msg;//这个是netty封装后的buf 性能明显是比之前的高的。
//        System.out.println("byteBuf.toString(CharsetUtil.UTF_8) = " + byteBuf.toString(CharsetUtil.UTF_8));



    }
发布了66 篇原创文章 · 获赞 0 · 访问量 789

猜你喜欢

转载自blog.csdn.net/Be_With_I/article/details/104037152
4-1