netty 4-2 定时任务

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

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

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



    }

现在如果是定时任务,我们因为用了eventLoop所以,就一个线程,先要执行完成上面的任务之后,才会执行定时任务,所以等待时间是有可能被加长的。

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

猜你喜欢

转载自blog.csdn.net/Be_With_I/article/details/104037490