NioEventLoop处理异步任务/定时任务
1.异步任务
这里直接在Netty快速入门(一) 自定义的服务器端handler中进行异步任务
/**
* 因为Netty是基于事件处理的
* 所以该类用于读写连接等事件处理的,每一种事件都有不用的处理方法,继承SimpleChannelInboundHandler,泛型为接收的数据类型
* */
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
/**
* 读取客户端发送的数据
* */
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println("服务器端接收到数据:"+" "+s);
//获取eventLoop用于发送定时任务或者异步任务
EventLoop eventLoop = channelHandlerContext.channel().eventLoop();
channelHandlerContext.channel().writeAndFlush("[当前时间:"+simpleDateFormat.format(new Date())+"]"+"异步任务将在3秒后发送\n");
eventLoop.execute(()->{
try {
//三秒钟
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
channelHandlerContext.channel().writeAndFlush("[当前时间:"+simpleDateFormat.format(new Date())+"]"+"我是异步任务\n");
});
//获取到channel用于回复客户端
channelHandlerContext.channel().writeAndFlush("你好,客户端\n");
}
/**
* 发生异常后,关闭客户端连接
* */
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
如果异步操作没问题应该是入下输出顺序
结果可以看到实现了异步处理
2.定时任务
**
* 因为Netty是基于事件处理的
* 所以该类用于读写连接等事件处理的,每一种事件都有不用的处理方法,继承SimpleChannelInboundHandler,泛型为接收的数据类型
* */
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
/**
* 读取客户端发送的数据
* */
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println("服务器端接收到数据:"+" "+s);
//获取eventLoop用于发送定时任务或者异步任务
EventLoop eventLoop = channelHandlerContext.channel().eventLoop();
channelHandlerContext.channel().writeAndFlush("[当前时间:"+simpleDateFormat.format(new Date())+"]"+"定时任务将在5秒后发送\n");
eventLoop.schedule(new Runnable() {
@Override
public void run() {
channelHandlerContext.channel().writeAndFlush("[当前时间:"+simpleDateFormat.format(new Date())+"]"+"我是定时任务\n");
}
},5, TimeUnit.SECONDS);
//获取到channel用于回复客户端
channelHandlerContext.channel().writeAndFlush("你好,客户端\n");
}
/**
* 发生异常后,关闭客户端连接
* */
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
如果定时任务执行没问题的话输出顺序应该如下
看一下结果可以看出来定时任务也正常执行了