How to use ChannelTrafficShapingHandler in Netty 4

2019-05-20 00:19发布

I need to push a big file to client, but I want to limit the speed(such as 100Kb/s), how to use 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()
                               );
                   }
               });

This demo doesn't work, why?

1条回答
Root(大扎)
2楼-- · 2019-05-20 00:56

Did you manage the channel write capability in your FileServerHandler ?

As stated in Netty API for 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.

And the initialization:

  • First item is Write limit in B/s (Here 1 is strongly not recommended, something close to 1024 is minimal, for 1KB/s)
  • second item is Read limit in B/S (Here 1 is strongly not recommended, something close to 1024 is minimal, for 1KB/s, or 0 for no limit)
  • First item is interval check in ms (Here 1L means every ms, which is strongly not recommended, something close to 1000 is minimal, for every 1s)

You can see an example (using Discard example) here, in particular:

查看更多
登录 后发表回答