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));



    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值