Netty: 注意不要为java.nio.channels.ClosedChannelException浪费时间

服务端Netty在测试时遇到大量java.nio.channels.ClosedChannelException异常。有可能是你的代码有问题,也有可能仅是客户端主动关闭了连接,导致服务端的写失败。

比如,你如果在浏览器里按住F5不停刷新,就会出现大量这样的错误;但用curl/wget高并发地做压测,却并没有这种问题。

如果无聊的用户拼命刷你导致服务端出现大量这种异常怎么办? 一是限流,二是让服务端在写数据之前判断一下channel是否已关闭。

		if (!channel.isConnected()) {
			if (logger.isWarnEnabled()) {
				logger.warn("Failed to write any response because the channel is not connected any more. Maybe the client has closed the connection? ");
			}
			return;
		}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.