这个问题是在一个群友做压力测试的时候发现的。使用客户端和netty创建一条连接,然后写了一个for循环不停的给服务器发送1500条信息,发现返回只有几百条。另外几百条不知道哪去了。查看代码,发现在服务器发送前做了一个判断:
![](https://upload-images.jianshu.io/upload_images/3793531-5ec2c4ed2294e27f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
通过查看源码,问题就在isWriteable()里面,下面看一下源码,在AbstractChannel里面:
![](https://upload-images.jianshu.io/upload_images/3793531-9f213da750f127d1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
再看buf.isWritebale()的实现:
![](https://upload-images.jianshu.io/upload_images/3793531-55bda21d64e9dc34.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
这里有一个变量,控制了是否可以写,那这个变量什么时候发生变化呢,我们接着找,先看看是什么情况下被修改为非0的
![](https://upload-images.jianshu.io/upload_images/3793531-abc56b65c049d1b5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
这个方法是在这里被调用 的:
![](https://upload-images.jianshu.io/upload_images/3793531-9e88312043c6a01f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
这个方法是用来接收发送数据的缓存的,从这里可以看出,当缓存的数据长库大于channel.config.getWriteBufferHighWaterMark()的时候,就不能再写了。这是一种限流 措施,防止数据写入太大,导致消息堆积,内存不足的情况。
我们看到这个值是在channel config中配置的,那么就可以在channel config中修改这个值,
ctx.channel().config().setWriteBufferHighWaterMark(1024*1024 * 8);
也可以在服务启动的时候设置:
![](https://upload-images.jianshu.io/upload_images/3793531-e904cb2dcb76c92e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
给孩子的礼物: