## 系统保护规则 (SystemRule) Sentinel 系统自适应限流从整体维度对应用入口流量进行控制,结合应用的 Load、总体平均 RT、入口 QPS 和线程数等几个维度的监控指标,让系统的入口流量和系统的负载达到一个平衡,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。 ![](https://img.kancloud.cn/fb/56/fb56e4c24f0602583b861d5b1f737c60_1833x508.png) 系统保护规则是从应用级别的入口流量进行控制,从单台机器的总体 Load、RT、入口 QPS 和线程数四个维度监控应用数据,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。 系统保护规则是应用整体维度的,而不是资源维度的,并且**仅对入口流量生效**。入口流量指的是进入应用的流量(`EntryType.IN`),比如 Web 服务或 Dubbo 服务端接收的请求,都属于入口流量。 系统规则支持以下的阈值类型: \- **Load**(仅对 Linux/Unix-like 机器生效):当系统 load1 超过阈值,且系统当前的并发线程数超过系统容量时才会触发系统保护。系统容量由系统的 `maxQps * minRt` 计算得出。设定参考值一般是 `CPU cores * 2.5`。 \- **CPU usage**(1.5.0+ 版本):当系统 CPU 使用率超过阈值即触发系统保护(取值范围 0.0-1.0)。 \- **RT**:当单台机器上所有入口流量的平均 RT 达到阈值即触发系统保护,单位是毫秒。 \- **线程数**:当单台机器上所有入口流量的并发线程数达到阈值即触发系统保护。 \- **入口 QPS**:当单台机器上所有入口流量的 QPS 达到阈值即触发系统保护。 核心代码 ```java com.alibaba.csp.sentinel.slots.system.SystemRuleManager ``` ```java     private static boolean checkBbr(int currentThread) {         if (currentThread > 1 &&             currentThread > Constants.ENTRY_NODE.maxSuccessQps() * Constants.ENTRY_NODE.minRt() / 1000) {             return false;         }         return true;     } ``` ```java  public static void checkSystem(ResourceWrapper resourceWrapper) throws BlockException {         // Ensure the checking switch is on.         if (!checkSystemStatus.get()) {             return;         }         // for inbound traffic only         if (resourceWrapper.getEntryType() != EntryType.IN) {             return;         }         // total qps         double currentQps = Constants.ENTRY_NODE == null ? 0.0 : Constants.ENTRY_NODE.successQps();         if (currentQps > qps) {             throw new SystemBlockException(resourceWrapper.getName(), "qps");         }         // total thread         int currentThread = Constants.ENTRY_NODE == null ? 0 : Constants.ENTRY_NODE.curThreadNum();         if (currentThread > maxThread) {             throw new SystemBlockException(resourceWrapper.getName(), "thread");         }         double rt = Constants.ENTRY_NODE == null ? 0 : Constants.ENTRY_NODE.avgRt();         if (rt > maxRt) {             throw new SystemBlockException(resourceWrapper.getName(), "rt");         }         // load. BBR algorithm.         if (highestSystemLoadIsSet && getCurrentSystemAvgLoad() > highestSystemLoad) {             if (!checkBbr(currentThread)) {                 throw new SystemBlockException(resourceWrapper.getName(), "load");             }         }         // cpu usage         if (highestCpuUsageIsSet && getCurrentCpuUsage() > highestCpuUsage) {             if (!checkBbr(currentThread)) {                 throw new SystemBlockException(resourceWrapper.getName(), "cpu");             }         }     } ``` ## 系统规则案例 ![](https://img.kancloud.cn/87/ab/87ab23376117fcc8e89e73fa37f212f3_803x726.png)