Netty模型之ScheduledTaskQueue定时任务队列
服务端处理器,其他模块与下列案例一致
https://blog.csdn.net/weixin_44371237/article/details/122391777?spm=1001.2014.3001.5501
public class ServerHandler extends ChannelInboundHandlerAdapter {
//当通道有读事件,会触发
//ChannelHandlerContext上下文,含有管道pipeline与通道channel
//Object msg 通道数据
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// //阻塞,包括以下的channelReadComplete
// Thread.sleep(10000);
// //将msg转成ByteBuf
// ByteBuf buf = (ByteBuf) msg;
// System.out.println(buf.toString(CharsetUtil.UTF_8));
// System.out.println("读到的线程 "+Thread.currentThread().getName());
// //防止阻塞,自定义任务,下面channelReadComplete不会被阻塞
// //采用TaskQueue任务队列
// ctx.channel().eventLoop().execute(new Runnable() {
// @Override
// public void run() {
// try {
// Thread.sleep(10000);
// //将msg转成ByteBuf
// ByteBuf buf = (ByteBuf) msg;
// System.out.println(LocalDateTime.now() + buf.toString(CharsetUtil.UTF_8));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// });
// //以下要20秒才能发送
// ctx.channel().eventLoop().execute(new Runnable() {
// @Override
// public void run() {
// try {
// Thread.sleep(10000);
// //将msg转成ByteBuf
// ByteBuf buf = (ByteBuf) msg;
// System.out.println(LocalDateTime.now() + buf.toString(CharsetUtil.UTF_8));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// });
//采用ScheduledTaskQueue定时任务队列
ctx.channel().eventLoop().schedule(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10000);
//将msg转成ByteBuf
ByteBuf buf = (ByteBuf) msg;
System.out.println(LocalDateTime.now() + buf.toString(CharsetUtil.UTF_8));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 10, TimeUnit.SECONDS);
}
//数据读取完毕
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//将数据写入缓冲区并刷新 write+flush
//对发送数据编码
ctx.writeAndFlush(Unpooled.copiedBuffer("服务端:您好", CharsetUtil.UTF_8));
}
//处理异常,关闭通道
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}