![](https://img.haomeiwen.com/i8491882/ec92ec1c2e0b0417.png)
image.png
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// 比如这里我们有一个非常耗时长的业务 - 异步执行 - 提交该 channel 对应的
// NIOEventLoop 的 taskQueue 中,
// 解决方案1 用户程序自定义的普通任务
ctx.channel().eventLoop().execute(() -> {
try {
Thread.sleep(10 * 1000);
ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(耗时1)", CharsetUtil.UTF_8));
} catch (InterruptedException e) {
System.out.println("发生异常:" + e.getMessage());
}
});
ctx.channel().eventLoop().execute(() -> {
try {
Thread.sleep(20 * 1000);
ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(耗时3)", CharsetUtil.UTF_8));
} catch (InterruptedException e) {
System.out.println("发生异常:" + e.getMessage());
}
});
// 用户自定义定时任务 - 该任务是提交到 scheduleTaskQueue 中
ctx.channel().eventLoop().schedule(() -> {
try {
Thread.sleep(5 * 1000);
ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端~(耗时2)", CharsetUtil.UTF_8));
} catch (InterruptedException e) {
System.out.println("发生异常:" + e.getMessage());
}
}, 5, TimeUnit.SECONDS);
System.out.println("go on...");
/*
System.out.println("服务器读取线程:" + Thread.currentThread().getName());
System.out.println("server ctx = " + ctx);
System.out.println("看看 channel 和 pipeline 的关系");
Channel channel = ctx.channel();
ChannelPipeline pipeline = ctx.pipeline(); // 本质是一个双向链表,出战入栈问题
// 将 msg 转成一个 ByteBuf
// ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer
ByteBuf buf = (ByteBuf) msg;
System.out.println("客户端发送的消息是:" + buf.toString(CharsetUtil.UTF_8));
System.out.println("客户端地址:" + channel.remoteAddress());
*/
}
![](https://img.haomeiwen.com/i8491882/b88cd69d40ac6fd3.png)
image.png
![](https://img.haomeiwen.com/i8491882/d614305ec1892f20.png)
image.png
![](https://img.haomeiwen.com/i8491882/1126a45c04f8c90a.png)
image.png
![](https://img.haomeiwen.com/i8491882/8c902aab9e252e71.png)
image.png
![](https://img.haomeiwen.com/i8491882/cf8b92cbd7839c1d.png)
image.png
![](https://img.haomeiwen.com/i8491882/8e4c93dbf99f84c4.png)
image.png
网友评论