Netty | 流量整形

什么是流量整形?

  • 消除流量波峰,减少对下游系统的冲击;

Netty 中流量整形逻辑概述

  • Netty 对读写流控的判断是基于固定窗口(相对于滑动窗口、令牌)的判断,按照一定时间段 checkInterval (1s) 来统计;
  • 当 writeLimit / readLimit 设置为 0 时,表示关闭写 / 读整形;

等待时间的范围控制

  • 10ms(MINIMAL_WAIT) -> 15s(maxTime);

读流控的实现逻辑

  • 取消读事件监听;
  • 让读缓冲区满;
  • 然后对端写缓冲区满;
  • 然后对端写不进入;
  • 对端对数据进行丢弃或者减缓发送速率;

写流控的实现逻辑

  • 待发数据写入 Queue;
  • 等待超过 4s(maxWriteDelay) || 单个 channel 缓存的数据超过 4M(maxWriteSize) || 所有缓存数据超过 400M(maxGlobalWriteSize) 时修改写状态为不可写;

流量整形的使用

  • ChannelTrafficShappingHandler
  • GlobalTrafficShapingHandler @Sharable
  • GlobalChannelTrafficShappingHandler | @Sharable | 构造器参数见如下代码:
/**
 * Create a new instance.
 *
 * @param executor
 *            the {@link ScheduledExecutorService} to use for the {@link TrafficCounter}.
 * @param writeGlobalLimit
 *            0 or a limit in bytes/s
 * @param readGlobalLimit
 *            0 or a limit in bytes/s
 * @param writeChannelLimit
 *            0 or a limit in bytes/s
 * @param readChannelLimit
 *            0 or a limit in bytes/s
 * @param checkInterval
 *            The delay between two computations of performances for
 *            channels or 0 if no stats are to be computed.
 * @param maxTime
 *            The maximum delay to wait in case of traffic excess.
 */
public GlobalChannelTrafficShapingHandler(ScheduledExecutorService executor,
        long writeGlobalLimit, long readGlobalLimit,
        long writeChannelLimit, long readChannelLimit,
        long checkInterval, long maxTime) {
    super(writeGlobalLimit, readGlobalLimit, checkInterval, maxTime);
    createGlobalTrafficCounter(executor);
    this.writeChannelLimit = writeChannelLimit;
    this.readChannelLimit = readChannelLimit;
}
  • 使用流量整形的代码示例:
// Netty 提供的用于流量整形的 Handler
final GlobalTrafficShapingHandler globalTrafficShapingHandler
        // 这里需要的 Executor 比较轻量级,只是服务于 TrafficCounter,可以直接复用上面的 executors,也可以直接 new 出来;
        // 读写控制都定成 100M
        = new GlobalTrafficShapingHandler(new NioEventLoopGroup(), 100 * 1024 * 1024, 100 * 1024 * 1024);

// 流量整形的 Handler 要放到靠前一点的位置
pipeline.addLast("TShandler", globalTrafficShapingHandler);

是否需要使用流量整形的考量

  • 如果部署的的机器数量充足,或者没多少流量,则无需使用流量整形;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值