netty - 如何在 Netty 4+ 中使用 ChannelTrafficShapingHandler?

标签 netty rate-limiting

我需要向客户端推送一个大文件,但是我想限制速度(比如100Kb/s),如何使用ChannelTrafficShapingHandler?

ServerBootstrap b = new ServerBootstrap();
              b.group(bossGroup, workerGroup)
               .channel(NioServerSocketChannel.class)
               .option(ChannelOption.SO_BACKLOG, 100)
               .handler(new LoggingHandler(LogLevel.INFO))
               .childHandler(new ChannelInitializer<SocketChannel>() {
                   @Override
                   public void initChannel(SocketChannel ch) throws Exception {
                       ChannelPipeline p = ch.pipeline();

                       p.addLast(
                               new StringEncoder(CharsetUtil.UTF_8),
                               new LineBasedFrameDecoder(8192),
                               new StringDecoder(CharsetUtil.UTF_8),
                               new ChannelTrafficShapingHandler(1,1,10L),
                               new ChunkedWriteHandler(),
                               new FileServerHandler()
                               );
                   }
               });

这个演示不起作用,为什么?

最佳答案

您是否在 FileServerHandler 中管理 channel 写入功能?

如 Netty API 中所述 ChannelTrafficShapingHandler

In your handler, you should consider to use the channel.isWritable() and channelWritabilityChanged(ctx) to handle writability, or through future.addListener(new GenericFutureListener()) on the future returned by ctx.write().

You shall also consider to have object size in read or write operations relatively adapted to the bandwidth you required: for instance having 10 MB objects for 10KB/s will lead to burst effect, while having 100 KB objects for 1 MB/s should be smoothly handle by this TrafficShaping handler.

和初始化:

  • 第一项是以 B/s 为单位的写入限制(这里强烈不推荐 1,接近 1024 的东西是最小的,对于 1KB/s)
  • 第二项是B/S中的Read limit(这里强烈不推荐1,接近1024的最小值,1KB/s,0则无限制)
  • 第一项是以毫秒为单位的间隔检查(这里的 1L 表示每毫秒,强烈不推荐,接近 1000 的东西是最小的,每 1 秒)

可以看一个例子(使用Discard的例子)here ,特别是:

关于netty - 如何在 Netty 4+ 中使用 ChannelTrafficShapingHandler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34326230/

相关文章:

java - Netty - getRemoteAddress 每次返回不同的端口

java - 在Netty中发送和接收ArrayList对象或Array对象

java - Netty Channel.write 线程安全吗?

IIS 动态 IP 限制白名单

javascript - 如何在 Javascript 中将按钮的点击次数限制为每分钟一次

java - 无法使用 Netty 将字节 [] 发送到服务器

java - Netty - 如何测试客户端/服务器版本号

python - 解决错误 104 和 Twitter 速率限制

amazon-web-services - 限制/阻止 MQTT 从 AWS IoT 中的事物发布限制

elasticsearch - 分布式爬虫和限速/流量控制