


// 源码位置: io.netty.handler.timeout.IdleStateHandler#write@Overridepublic void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {if (writerIdleTimeNanos > 0 || allIdleTimeNanos > 0) {// 业务线程在执行写入的时候,最终会将写操作封装成一个写任务放入IO线程的队列中.同时它会设置一个监听,用于回调使用.ctx.write(msg, promise.unvoid()).addListener(writeListener);} else {ctx.write(msg, promise);}}private final ChannelFutureListener writeListener = new ChannelFutureListener() {@Overridepublic void operationComplete(ChannelFuture future) throws Exception {lastWriteTime = ticksInNanos();firstWriterIdleEvent = firstAllIdleEvent = true;}};

A点是我们上次写空闲的检测时间点,B点是我们最后一次写操作的时间点,假如此时触发了写空闲检测,时间点在C点.


// 源码位置: io.netty.handler.timeout.IdleStateHandler.WriterIdleTimeoutTaskprivate final class WriterIdleTimeoutTask extends AbstractIdleTask {WriterIdleTimeoutTask(ChannelHandlerContext ctx) {super(ctx);}@Overrideprotected void run(ChannelHandlerContext ctx) {long lastWriteTime = IdleStateHandler.this.lastWriteTime;long nextDelay = writerIdleTimeNanos - (ticksInNanos() - lastWriteTime);if (nextDelay <= 0) {writerIdleTimeout = schedule(ctx, this, writerIdleTimeNanos, TimeUnit.NANOSECONDS);boolean first = firstWriterIdleEvent;firstWriterIdleEvent = false;try {// 这个地方就是用于是否考虑写操作慢的情况if (hasOutputChanged(ctx, first)) {return;}IdleStateEvent event = newIdleStateEvent(IdleState.WRITER_IDLE, first);channelIdle(ctx, event);} catch (Throwable t) {ctx.fireExceptionCaught(t);}} else {writerIdleTimeout = schedule(ctx, this, nextDelay, TimeUnit.NANOSECONDS);}}}
文章转载自Netty历险记,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




