Sentinel统计线程,QPS,RT的方式

一、Sentinel是阿里开源产品,用于流量监控和管理。

二、对于流量控制,可以通过限制线程数和QPS实现限流

1. 资源进入Sentinel的方式

Entry entry = null;
try {
   entry = SphU.entry(resourceName, entryType);
   Object result = pjp.proceed();
   return result;
} catch (BlockException ex) {
   
} catch (Throwable ex) {
  
} finally {
   if (entry != null) {
       entry.exit();
   }
}

Entry对象负责进入和退出的管理,进入后增加线程计数及访问记录,退出后减少线程计数及访问记录。

2. Sentinel是通过一组ProcessorSlot链组成ProcessorSlotChain来责任调用。

public ProcessorSlotChain build() {
        ProcessorSlotChain chain = new DefaultProcessorSlotChain();
        chain.addLast(new NodeSelectorSlot());
        chain.addLast(new ClusterBuilderSlot());
        chain.addLast(new LogSlot());
        chain.addLast(new StatisticSlot());
        chain.addLast(new SystemSlot());
        chain.addLast(new AuthoritySlot());
        chain.addLast(new FlowSlot());
        chain.addLast(new DegradeSlot());
        return chain;
 }

调用的顺序是:NodeSelectorSlot --> ClusterBuilderSlot --> LogSlot --> SystemSlot --> AuthoritySlot --> FlowSlot --> DegradeSlot --> StatisticSlot 

3. 关于线程、QPS、RT的计算

查看StatisticSlot

entry 方法中主要是调用StatisticNode的increaseThreadNum, addPassRequest方法

exit 方法中主要是调用StatisticNode的 rt ,decreaseThreadNum方法

在StatisticNode中,可以看到几个属性:

  两个时间窗口,一个线程计数器

private transient volatile Metric rollingCounterInSecond = new ArrayMetric(1000 / 2,1);
private transient Metric rollingCounterInMinute = new ArrayMetric(1000, 60);
private AtomicInteger curThreadNum = new AtomicInteger(0);

线程计数器很好理解,entry时 根据FlowRule 校验 ,增加该值,exit时减小该值。

QPS就是rollingCounterInSecond当前时间窗口的各QPS计数器值:

  有passQPS , successQPS, blockQPS, exceptionQPS ,totalQPS(passQPS+blockQPS)

平均RT(1s平均响应次数) 是rollingCounterInSecond当前窗口的 RT总值除以 success次数。

  一次RT: exit时的时间值 减去  entry时的时间值。

4. 时间窗口定义(时间单位均为毫秒, / 为整除):

  间隔时间,窗口长度。 

  间隔时间 / 窗口长度 ---> 窗口数组长度

  当前时间 / 窗口长度 % 窗口数组长度  ----> 定位到当前窗口

  窗口长度 × (当前时间 / 窗口长度) ----> 当前窗口的起始时间

原文地址:https://www.cnblogs.com/selfchange/p/9979943.html