LeapArray分析
我们知道StatisticSlot是Sentinel的核心插槽之一,用于统计实时的数据,后续大部分限流降级的规则都是基于StatisticSlot统计的数据来进行检查。因此对于它是如何统计的,需要了解下。
Sentinel 底层采用高性能的滑动窗口数据结构 LeapArray 来统计实时的秒级指标数据
- 它有4个关键的属性。
- windowLengthInMs 每个窗口有多少毫秒
- sampleCount 窗口数量
- intervalInMs 要统计的间隔时长
- array 即统计的数据存放的地方
其关系如下
2 计算当前的窗口位置,以及窗口开始时间
便于数据存储
- 获取当前的ms值
- 当前值除以windowLengthInMs,即窗口间隔,然后对sampleCount取余
就是看散装的时间如何划分,就知道当前在哪个node记录数据中。。。
- 当前时间窗口过期之后,将当前窗口的startTime指向新的窗口开始时间。
- 更新窗口startTime
- 重置窗口中存储的value,即上个窗口过期
4 滑动窗口只是用于计算窗口,而窗口中的数据存储结构用的是MetricBucket。其统计了6个维度的数据:
- 每个创建都会存储一个MetricBucket
- 每个MetricBucket可以统计如下数据
public enum MetricEvent {
/**
* Normal pass.
*/
PASS,
/**
* Normal block.
*/
BLOCK,
EXCEPTION,
SUCCESS,
RT,
/**
* Passed in future quota (pre-occupied, since 1.5.0).
*/
OCCUPIED_PASS
}
5 StasticSlot统计时机
- 在entry时增加TheadNum, Pass,如果遇到异常则增加BlockQPS,遇到特殊异常会增加Exception数量
- 在exit时统计SUCCESS和RT
public class StatisticSlot extends AbstractLinkedProcessorSlot<DefaultNode> {
@Override
public void entry(Context context, ResourceWrapper resourceWrapper, DefaultNode node, int count,
boolean prioritized, Object... args) throws Throwable {
try {
// Do some checking.
fireEntry(context, resourceWrapper, node, count, prioritized, args);
// Request passed, add thread count and pass count.
node.increaseThreadNum();
node.addPassRequest(count);
...
} catch (BlockException e) {
// Blocked, set block exception to current entry.
context.getCurEntry().setError(e);
// Add block count.
node.increaseBlockQps(count);
throw e;
} catch (Throwable e) {
// Unexpected error, set error to current entry.
context.getCurEntry().setError(e);
// This should not happen.
node.increaseExceptionQps(count);
throw e;
}
}
@Override
public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
DefaultNode node = (DefaultNode)context.getCurNode();
// Record response time and success count.
node.addRtAndSuccess(rt, count);
node.decreaseThreadNum();
fireExit(context, resourceWrapper, count);
}
}