找回密码
 立即注册
首页 业界区 业界 Sentinel源码—4.FlowSlot实现流控的原理

Sentinel源码—4.FlowSlot实现流控的原理

任佳湍 2025-6-2 21:31:36
大纲
1.FlowSlot根据流控规则对请求进行限流
2.FlowSlot实现流控规则的快速失败效果的原理
3.FlowSlot实现流控规则中排队等待效果的原理
4.FlowSlot实现流控规则中Warm Up效果的原理
 
1.FlowSlot根据流控规则对请求进行限流
(1)流控规则FlowRule的配置Demo
(2)注册流控监听器和加载流控规则
(3)FlowSlot根据流控规则对请求进行限流
 
(1)流控规则FlowRule的配置Demo
从下图可知,流控规则包含以下属性:
1.webp
一.规则id、资源名、针对来源
这三个属性是所有规则共有的属性,会分别封装到AbstractRule的id、resource、limitApp字段中,各个具体的规则子类都会继承AbstractRule类。
 
二.阈值类型
阈值类型包括QPS和并发线程数两个选项,对应FlowRule中的字段为grade。
 
三.单机阈值
单机阈值也就是限流阈值。无论是基于QPS还是并发线程数,都要设置限流阈值,对应FlowRule中的字段为count。
 
四.是否集群
是否集群是一个boolean类型的字段,对应FlowRule中的字段为clusterMode。true表示开启集群模式,false表示单机模式;
 
五.流控模式
流控模式有三种:直接模式、关联模式和链路模式,对应FlowRule中的字段为strategy。
 
六.关联资源
当流控模式选择为关联时,此值含义是关联资源,当流控模式选择为链路时,此值含义是入口资源。所以仅当流控模式选择关联和链路时,才对应FlowRule中的字段为refResource。
 
七.流控效果
流控效果有三种:快速失败、Warm Up、排队等待。还有一个选项未在页面上显示,即Warm Up和排队等待的结合体。也就是Warm Up + 排队等待,对应FlowRule中的字段为controlBehavior。
 
八.流控控制器
由于流控有多种模式,而每种模式都会对应一个模式流量整形控制器。所以流控规则FlowRule中会有一个字段TrafficShapingController,用来实现不同流控模式下的不同流控效果。
 
九.预热时长
此选项仅在流控效果选择Warm Up时出现,表示Warm Up的时长,对应FlowRule中的字段为warmUpPeriodSec。
 
十.超时时间
此选项仅在流控效果选择排队等待时出现,表示超出流控阈值后,排队等待多久才抛出异常,对应FlowRule中的字段为maxQueueingTimeMs。
  1. public abstract class AbstractRule implements Rule {
  2.     //rule id. 规则id
  3.     private Long id;
  4.     //Resource name. 资源名称
  5.     private String resource;
  6.     //针对来源,默认是default
  7.     //多个来源使用逗号隔开,比如黑名单规则,限制userId是1和3的访问,那么就设置limitApp为"1,3"
  8.     //Application name that will be limited by origin.
  9.     //The default limitApp is {@code default}, which means allowing all origin apps.
  10.     //For authority rules, multiple origin name can be separated with comma (',').
  11.     private String limitApp;
  12.     ...
  13. }
  14. //规则id、资源名(resource)、针对来源(limitApp),这三个字段在父类AbstractRule里
  15. //Each flow rule is mainly composed of three factors: grade, strategy and controlBehavior:
  16. //The grade represents the threshold type of flow control (by QPS or thread count).
  17. //The strategy represents the strategy based on invocation relation.
  18. //The controlBehavior represents the QPS shaping behavior (actions on incoming request when QPS exceeds the threshold.
  19. public class FlowRule extends AbstractRule {
  20.     public FlowRule() {
  21.         super();
  22.         setLimitApp(RuleConstant.LIMIT_APP_DEFAULT);
  23.     }
  24.    
  25.     public FlowRule(String resourceName) {
  26.         super();
  27.         setResource(resourceName);
  28.         setLimitApp(RuleConstant.LIMIT_APP_DEFAULT);
  29.     }
  30.    
  31.     //The threshold type of flow control (0: thread count, 1: QPS).
  32.     //阈值类型:1代表QPS;0代表并发线程数
  33.     private int grade = RuleConstant.FLOW_GRADE_QPS;
  34.    
  35.     //Flow control threshold count.
  36.     //单机阈值:也就是限流数
  37.     private double count;
  38.    
  39.     //Flow control strategy based on invocation chain.
  40.     //流控模式:0代表直接;1代表关联;2代表链路
  41.     //RuleConstant#STRATEGY_DIRECT for direct flow control (by origin);
  42.     //RuleConstant#STRATEGY_RELATE for relevant flow control (with relevant resource);
  43.     //RuleConstant#STRATEGY_CHAIN for chain flow control (by entrance resource).
  44.     private int strategy = RuleConstant.STRATEGY_DIRECT;
  45.    
  46.     //关联资源,当流控模式选择为关联时,此值含义是关联资源,当流控模式选择为链路时,此值含义是入口资源
  47.     //Reference resource in flow control with relevant resource or context.
  48.     private String refResource;
  49.    
  50.     //Rate limiter control behavior.
  51.     //0. default(reject directly), 1. warm up, 2. rate limiter, 3. warm up + rate limiter
  52.     //流控效果:0代表快速失败, 1代表Warm Up, 2代表排队等待, 3代表Warm Up + 排队等待
  53.     private int controlBehavior = RuleConstant.CONTROL_BEHAVIOR_DEFAULT;
  54.    
  55.     //预热时长:只有当流控效果选择为Warm Up时才会出现
  56.     private int warmUpPeriodSec = 10;
  57.     //Max queueing time in rate limiter behavior.
  58.     //超时时间:只有当流控效果选择排队等待时才会出现
  59.     private int maxQueueingTimeMs = 500;
  60.     //是否集群:默认false表示单机
  61.     private boolean clusterMode;
  62.     //Flow rule config for cluster mode.
  63.     //集群配置
  64.     private ClusterFlowConfig clusterConfig;
  65.     //The traffic shaping (throttling) controller.
  66.     //流量整形控制器:实现[流控效果]的四种不同模式
  67.     private TrafficShapingController controller;
  68.     ...
  69. }
  70. public class FlowQpsDemo {
  71.     private static final String KEY = "abc";
  72.     private static AtomicInteger pass = new AtomicInteger();
  73.     private static AtomicInteger block = new AtomicInteger();
  74.     private static AtomicInteger total = new AtomicInteger();
  75.     private static volatile boolean stop = false;
  76.     private static final int threadCount = 32;
  77.     private static int seconds = 60 + 40;
  78.     public static void main(String[] args) throws Exception {
  79.         //初始化QPS的流控规则
  80.         initFlowQpsRule();
  81.         //启动线程定时输出信息
  82.         tick();
  83.         //first make the system run on a very low condition
  84.         //模拟QPS为32时的访问场景
  85.         simulateTraffic();
  86.         System.out.println("===== begin to do flow control");
  87.         System.out.println("only 20 requests per second can pass");
  88.     }
  89.     private static void initFlowQpsRule() {
  90.         List<FlowRule> rules = new ArrayList<FlowRule>();
  91.         FlowRule rule1 = new FlowRule();
  92.         rule1.setResource(KEY);
  93.         //设置QPS的限制为20
  94.         rule1.setCount(20);
  95.         rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
  96.         rule1.setLimitApp("default");
  97.         rules.add(rule1);
  98.         //加载流控规则
  99.         FlowRuleManager.loadRules(rules);
  100.     }
  101.     private static void simulateTraffic() {
  102.         for (int i = 0; i < threadCount; i++) {
  103.             Thread t = new Thread(new RunTask());
  104.             t.setName("simulate-traffic-Task");
  105.             t.start();
  106.         }
  107.     }
  108.     private static void tick() {
  109.         Thread timer = new Thread(new TimerTask());
  110.         timer.setName("sentinel-timer-task");
  111.         timer.start();
  112.     }
  113.     static class TimerTask implements Runnable {
  114.         @Override
  115.         public void run() {
  116.             long start = System.currentTimeMillis();
  117.             System.out.println("begin to statistic!!!");
  118.             long oldTotal = 0;
  119.             long oldPass = 0;
  120.             long oldBlock = 0;
  121.             while (!stop) {
  122.                 try {
  123.                     TimeUnit.SECONDS.sleep(1);
  124.                 } catch (InterruptedException e) {
  125.                
  126.                 }
  127.                 long globalTotal = total.get();
  128.                 long oneSecondTotal = globalTotal - oldTotal;
  129.                 oldTotal = globalTotal;
  130.                 long globalPass = pass.get();
  131.                 long oneSecondPass = globalPass - oldPass;
  132.                 oldPass = globalPass;
  133.                 long globalBlock = block.get();
  134.                 long oneSecondBlock = globalBlock - oldBlock;
  135.                 oldBlock = globalBlock;
  136.                 System.out.println(seconds + " send qps is: " + oneSecondTotal);
  137.                 System.out.println(TimeUtil.currentTimeMillis() + ", total:" + oneSecondTotal + ", pass:" + oneSecondPass + ", block:" + oneSecondBlock);
  138.                 if (seconds-- <= 0) {
  139.                     stop = true;
  140.                 }
  141.             }
  142.             long cost = System.currentTimeMillis() - start;
  143.             System.out.println("time cost: " + cost + " ms");
  144.             System.out.println("total:" + total.get() + ", pass:" + pass.get() + ", block:" + block.get());
  145.             System.exit(0);
  146.         }
  147.     }
  148.     static class RunTask implements Runnable {
  149.         @Override
  150.         public void run() {
  151.             while (!stop) {
  152.                 Entry entry = null;
  153.                 try {
  154.                     //调用entry()方法开始规则验证
  155.                     entry = SphU.entry(KEY);
  156.                     //token acquired, means pass
  157.                     pass.addAndGet(1);
  158.                 } catch (BlockException e1) {
  159.                     block.incrementAndGet();
  160.                 } catch (Exception e2) {
  161.                     //biz exception
  162.                 } finally {
  163.                     total.incrementAndGet();
  164.                     if (entry != null) {
  165.                         //完成规则验证调用exit()方法
  166.                         entry.exit();
  167.                     }
  168.                 }
  169.                 Random random2 = new Random();
  170.                 try {
  171.                     TimeUnit.MILLISECONDS.sleep(random2.nextInt(50));
  172.                 } catch (InterruptedException e) {
  173.                     //ignore
  174.                 }
  175.             }
  176.         }
  177.     }
  178. }
复制代码
(2)流量整形控制器DefaultController执行分析
流控效果为快速失败时,会调用DefaultController的canPass()方法。
 
问题一:其中的入参Node是如何选择的
Node的选择主要依赖于三个参数:FlowRule的limitApp、FlowRule的strategy、Context的origin,这三个参数分别表示流控规则的针对来源、流控模式和当前请求的来源。
 
情形一:如果limitApp和origin相等并且limitApp不是默认值default
  1. //One resources can have multiple rules.
  2. //And these rules take effects in the following order:
  3. //requests from specified caller
  4. //no specified caller
  5. public class FlowRuleManager {
  6.     //维护每个资源的流控规则列表,key是资源名称,value是资源对应的规则
  7.     private static volatile Map<String, List<FlowRule>> flowRules = new HashMap<>();
  8.     //饿汉式单例模式实例化流控规则的监听器对象
  9.     private static final FlowPropertyListener LISTENER = new FlowPropertyListener();
  10.     //监听器对象的管理器
  11.     private static SentinelProperty<List<FlowRule>> currentProperty = new DynamicSentinelProperty<List<FlowRule>>();
  12.     ...
  13.     static {
  14.         //将流控规则监听器注册到监听器管理器中
  15.         currentProperty.addListener(LISTENER);
  16.         startMetricTimerListener();
  17.     }
  18.    
  19.     //Load FlowRules, former rules will be replaced.
  20.     //加载流控规则
  21.     public static void loadRules(List<FlowRule> rules) {
  22.         //通知监听器管理器中的每一个监听器,规则已发生变化,需要重新加载规则配置
  23.         //其实就是更新FlowRuleManager规则管理器中的流控规则列表flowRules
  24.         currentProperty.updateValue(rules);
  25.     }
  26.    
  27.     private static final class FlowPropertyListener implements PropertyListener<List<FlowRule>> {
  28.         @Override
  29.         public synchronized void configUpdate(List<FlowRule> value) {
  30.             Map<String, List<FlowRule>> rules = FlowRuleUtil.buildFlowRuleMap(value);
  31.             if (rules != null) {
  32.                 flowRules = rules;
  33.             }
  34.             RecordLog.info("[FlowRuleManager] Flow rules received: {}", rules);
  35.         }
  36.         
  37.         @Override
  38.         public synchronized void configLoad(List<FlowRule> conf) {
  39.             Map<String, List<FlowRule>> rules = FlowRuleUtil.buildFlowRuleMap(conf);
  40.             if (rules != null) {
  41.                 flowRules = rules;
  42.             }
  43.             RecordLog.info("[FlowRuleManager] Flow rules loaded: {}", rules);
  44.         }
  45.     }
  46.     ...
  47. }
  48. public final class FlowRuleUtil {
  49.     private static final Function<FlowRule, String> extractResource = new Function<FlowRule, String>() {
  50.         @Override
  51.         public String apply(FlowRule rule) {
  52.             return rule.getResource();
  53.         }
  54.     };
  55.     ...
  56.     //Build the flow rule map from raw list of flow rules, grouping by resource name.
  57.     public static Map<String, List<FlowRule>> buildFlowRuleMap(List<FlowRule> list) {
  58.         return buildFlowRuleMap(list, null);
  59.     }
  60.    
  61.     //Build the flow rule map from raw list of flow rules, grouping by resource name.
  62.     public static Map<String, List<FlowRule>> buildFlowRuleMap(List<FlowRule> list, Predicate<FlowRule> filter) {
  63.         return buildFlowRuleMap(list, filter, true);
  64.     }
  65.    
  66.     //Build the flow rule map from raw list of flow rules, grouping by resource name.
  67.     public static Map<String, List<FlowRule>> buildFlowRuleMap(List<FlowRule> list, Predicate<FlowRule> filter, boolean shouldSort) {
  68.         return buildFlowRuleMap(list, extractResource, filter, shouldSort);
  69.     }
  70.    
  71.     //Build the flow rule map from raw list of flow rules, grouping by provided group function.
  72.     public static <K> Map<K, List<FlowRule>> buildFlowRuleMap(List<FlowRule> list, Function<FlowRule, K> groupFunction, Predicate<FlowRule> filter, boolean shouldSort) {
  73.         Map<K, List<FlowRule>> newRuleMap = new ConcurrentHashMap<>();
  74.         if (list == null || list.isEmpty()) {
  75.             return newRuleMap;
  76.         }
  77.         Map<K, Set<FlowRule>> tmpMap = new ConcurrentHashMap<>();
  78.         for (FlowRule rule : list) {
  79.             ...
  80.             //获取[流控效果]流量整形控制器TrafficShapingController
  81.             TrafficShapingController rater = generateRater(rule);
  82.             rule.setRater(rater);
  83.             //获取资源名
  84.             K key = groupFunction.apply(rule);
  85.             if (key == null) {
  86.                 continue;
  87.             }
  88.             //获取资源名对应的流控规则列表
  89.             Set<FlowRule> flowRules = tmpMap.get(key);
  90.             //将规则放到Map里,和当前资源绑定
  91.             if (flowRules == null) {
  92.                 //Use hash set here to remove duplicate rules.
  93.                 flowRules = new HashSet<>();
  94.                 tmpMap.put(key, flowRules);
  95.             }
  96.             flowRules.add(rule);
  97.         }
  98.         Comparator<FlowRule> comparator = new FlowRuleComparator();
  99.         for (Entry<K, Set<FlowRule>> entries : tmpMap.entrySet()) {
  100.             List<FlowRule> rules = new ArrayList<>(entries.getValue());
  101.             if (shouldSort) {
  102.                 //Sort the rules.
  103.                 Collections.sort(rules, comparator);
  104.             }
  105.             newRuleMap.put(entries.getKey(), rules);
  106.         }
  107.         return newRuleMap;
  108.     }
  109.    
  110.     private static TrafficShapingController generateRater(/*@Valid*/ FlowRule rule) {
  111.         //判断只有当阈值类型为QPS时才生效
  112.         if (rule.getGrade() == RuleConstant.FLOW_GRADE_QPS) {
  113.             //根据流控效果选择不同的流量整形控制器TrafficShapingController
  114.             switch (rule.getControlBehavior()) {
  115.                 case RuleConstant.CONTROL_BEHAVIOR_WARM_UP:
  116.                     //Warm Up预热模式——冷启动模式
  117.                     return new WarmUpController(rule.getCount(), rule.getWarmUpPeriodSec(), ColdFactorProperty.coldFactor);
  118.                 case RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER:
  119.                     //排队等待模式
  120.                     return new RateLimiterController(rule.getMaxQueueingTimeMs(), rule.getCount());
  121.                 case RuleConstant.CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER:
  122.                     //Warm Up + 排队等待模式
  123.                     return new WarmUpRateLimiterController(rule.getCount(), rule.getWarmUpPeriodSec(), rule.getMaxQueueingTimeMs(), ColdFactorProperty.coldFactor);
  124.                 case RuleConstant.CONTROL_BEHAVIOR_DEFAULT:
  125.                     //快速失败模式——Default默认模式
  126.                 default:
  127.                     //Default mode or unknown mode: default traffic shaping controller (fast-reject).
  128.             }
  129.         }
  130.         //默认模式:快速失败用的是DefaultController
  131.         return new DefaultController(rule.getCount(), rule.getGrade());
  132.     }
  133.     ...
  134. }
复制代码
情形二:limitApp值为默认的default
  1. @Spi(order = Constants.ORDER_FLOW_SLOT)
  2. public class FlowSlot extends AbstractLinkedProcessorSlot<DefaultNode> {
  3.     private final FlowRuleChecker checker;
  4.     private final Function<String, Collection<FlowRule>> ruleProvider = new Function<String, Collection<FlowRule>>() {
  5.         @Override
  6.         public Collection<FlowRule> apply(String resource) {
  7.             //Flow rule map should not be null.
  8.             Map<String, List<FlowRule>> flowRules = FlowRuleManager.getFlowRuleMap();
  9.             return flowRules.get(resource);
  10.         }
  11.     };
  12.    
  13.     public FlowSlot() {
  14.         this(new FlowRuleChecker());
  15.     }
  16.    
  17.     FlowSlot(FlowRuleChecker checker) {
  18.         AssertUtil.notNull(checker, "flow checker should not be null");
  19.         this.checker = checker;
  20.     }
  21.    
  22.     @Override
  23.     public void entry(Context context, ResourceWrapper resourceWrapper, DefaultNode node, int count, boolean prioritized, Object... args) throws Throwable {
  24.         //检查流控规则,count默认是1
  25.         checkFlow(resourceWrapper, context, node, count, prioritized);
  26.         fireEntry(context, resourceWrapper, node, count, prioritized, args);
  27.     }
  28.    
  29.     void checkFlow(ResourceWrapper resource, Context context, DefaultNode node, int count, boolean prioritized) throws BlockException {
  30.         //调用规则检查器FlowRuleChecker的checkFlow()方法进行检查,count默认是1
  31.         checker.checkFlow(ruleProvider, resource, context, node, count, prioritized);
  32.     }
  33.    
  34.     @Override
  35.     public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
  36.         fireExit(context, resourceWrapper, count, args);
  37.     }
  38. }
  39. //Rule checker for flow control rules.
  40. public class FlowRuleChecker {
  41.     public void checkFlow(Function<String, Collection<FlowRule>> ruleProvider, ResourceWrapper resource, Context context, DefaultNode node, int count, boolean prioritized) throws BlockException {
  42.         if (ruleProvider == null || resource == null) {
  43.             return;
  44.         }
  45.         //从Map中获取resource资源对应的流控规则列表
  46.         Collection<FlowRule> rules = ruleProvider.apply(resource.getName());
  47.         if (rules != null) {
  48.             //循环遍历每一个流控规则
  49.             for (FlowRule rule : rules) {
  50.                 //调用canPassCheck方法进行流控规则验证,判断此次请求是否命中针对resource资源配置的流控规则
  51.                 //传入的参数count默认是1
  52.                 if (!canPassCheck(rule, context, node, count, prioritized)) {
  53.                     throw new FlowException(rule.getLimitApp(), rule);
  54.                 }
  55.             }
  56.         }
  57.     }
  58.    
  59.     public boolean canPassCheck(/*@NonNull*/ FlowRule rule, Context context, DefaultNode node, int acquireCount) {
  60.         return canPassCheck(rule, context, node, acquireCount, false);
  61.     }
  62.    
  63.     public boolean canPassCheck(/*@NonNull*/ FlowRule rule, Context context, DefaultNode node, int acquireCount, boolean prioritized) {
  64.         //参数校验
  65.         String limitApp = rule.getLimitApp();
  66.         if (limitApp == null) {
  67.             return true;
  68.         }
  69.         //如果是集群模式,则执行passClusterCheck()方法
  70.         if (rule.isClusterMode()) {
  71.             return passClusterCheck(rule, context, node, acquireCount, prioritized);
  72.         }
  73.         //如果是单机模式,则执行passLocalCheck()方法,acquireCount默认是1
  74.         return passLocalCheck(rule, context, node, acquireCount, prioritized);
  75.     }
  76.    
  77.     private static boolean passLocalCheck(FlowRule rule, Context context, DefaultNode node, int acquireCount, boolean prioritized) {
  78.         //选择Node作为限流计算的依据
  79.         Node selectedNode = selectNodeByRequesterAndStrategy(rule, context, node);
  80.         if (selectedNode == null) {
  81.             return true;
  82.         }
  83.         //先通过FlowRule.getRater()方法获取流控规则对应的流量整形控制器
  84.         //然后调用TrafficShapingController.canPass()方法对请求进行检查,acquireCount默认是1
  85.         return rule.getRater().canPass(selectedNode, acquireCount, prioritized);
  86.     }
  87.    
  88.     //选择Node作为限流计算的依据
  89.     static Node selectNodeByRequesterAndStrategy(/*@NonNull*/ FlowRule rule, Context context, DefaultNode node) {
  90.         //The limit app should not be empty.
  91.         //获取流控规则中配置的"针对来源",默认是default
  92.         String limitApp = rule.getLimitApp();
  93.         //获取流控规则中配置的"流控模式",0代表直接,1代表关联,2代表链路
  94.         int strategy = rule.getStrategy();
  95.         //从context对象中获取当前请求的来源
  96.         String origin = context.getOrigin();
  97.         //情形一:当流控规则的针对来源(limitApp)与当前请求的来源(origin)相同时
  98.         //这种情况表示该限流规则针对特定来源进行限流
  99.         //如果配置了针对app1进行限流,那么app2就不会生效,这就是针对特定来源进行限流
  100.         if (limitApp.equals(origin) && filterOrigin(origin)) {
  101.             //如果流控规则中配置的"流控模式"是直接(RuleConstant.STRATEGY_DIRECT),则返回上下文中的Origin Node
  102.             //因为这种模式要求根据调用方的情况进行限流,而Origin Node包含了调用方的统计信息,所以选择Origin Node作为限流计算的依据
  103.             if (strategy == RuleConstant.STRATEGY_DIRECT) {
  104.                 //Matches limit origin, return origin statistic node.
  105.                 return context.getOriginNode();
  106.             }
  107.             //如果流控规则中配置的"流控模式"是关联、链路(RuleConstant.STRATEGY_RELATE或RuleConstant.STRATEGY_CHAIN),则调用selectReferenceNode()方法
  108.             //此方法会判断:
  109.             //如果"流控模式"是关联(RuleConstant.STRATEGY_RELATE),则返回关联资源的ClusterNode
  110.             //如果"流控模式"是链路(RuleConstant.STRATEGY_CHAIN),则返回DefaultNode
  111.             return selectReferenceNode(rule, context, node);
  112.         }
  113.         //情况二:当流控规则的针对来源(limitApp)是默认值(RuleConstant.LIMIT_APP_DEFAULT)时
  114.         //这种情况表示该流控规则对所有来源都生效
  115.         else if (RuleConstant.LIMIT_APP_DEFAULT.equals(limitApp)) {
  116.             //如果流控规则中配置的"流控模式"是直接(RuleConstant.STRATEGY_DIRECT),则返回当前请求的集群节点ClusterNode
  117.             //因为此时要求的是根据被调用资源的情况进行限流,而集群节点包含了被调用资源的统计信息,所以选择集群节点作为限流计算的依据
  118.             if (strategy == RuleConstant.STRATEGY_DIRECT) {
  119.                 //Return the cluster node.
  120.                 return node.getClusterNode();
  121.             }
  122.             //如果流控规则中配置的"流控模式"是关联、链路(RuleConstant.STRATEGY_RELATE或RuleConstant.STRATEGY_CHAIN),则调用selectReferenceNode()方法
  123.             //此方法会判断:
  124.             //如果"流控模式"是关联(RuleConstant.STRATEGY_RELATE),则返回关联资源的ClusterNode
  125.             //如果"流控模式"是链路(RuleConstant.STRATEGY_CHAIN),则返回DefaultNode
  126.             return selectReferenceNode(rule, context, node);
  127.         }
  128.         //情况三:当流控规则的针对来源(limitApp)是其他(RuleConstant.LIMIT_APP_OTHER),且当前请求的来源(origin)与流控规则的资源名(rule.getResource())不同时
  129.         //这种情况表示该流控规则针对除默认来源以外的其他来源进行限流,可实现个性化限流
  130.         //比如可以对app1进行个性化限流,对其他所有app进行整体限流
  131.         else if (RuleConstant.LIMIT_APP_OTHER.equals(limitApp) && FlowRuleManager.isOtherOrigin(origin, rule.getResource())) {
  132.             //如果流控规则中配置的"流控模式"是直接(RuleConstant.STRATEGY_DIRECT),则返回上下文中的来源节点(Origin Node)
  133.             //因为这种"流控模式"要求根据调用方的情况进行限流,而来源节点包含了调用方的统计信息,所以选择来源节点作为限流计算的依据
  134.             if (strategy == RuleConstant.STRATEGY_DIRECT) {
  135.                 return context.getOriginNode();
  136.             }
  137.             //如果流控规则中配置的"流控模式"是关联、链路(RuleConstant.STRATEGY_RELATE或RuleConstant.STRATEGY_CHAIN),则调用selectReferenceNode()方法
  138.             //此方法会判断:
  139.             //如果"流控模式"是关联(RuleConstant.STRATEGY_RELATE),则返回关联资源的ClusterNode
  140.             //如果"流控模式"是链路(RuleConstant.STRATEGY_CHAIN),则返回DefaultNode
  141.             return selectReferenceNode(rule, context, node);
  142.         }
  143.         return null;
  144.     }
  145.     //如果流控规则中配置的"流控模式"是关联(RuleConstant.STRATEGY_RELATE),则返回关联资源的ClusterNode
  146.     //如果流控规则中配置的"流控模式"是链路(RuleConstant.STRATEGY_CHAIN),则返回DefaultNode
  147.     static Node selectReferenceNode(FlowRule rule, Context context, DefaultNode node) {
  148.         String refResource = rule.getRefResource();
  149.         int strategy = rule.getStrategy();
  150.         if (StringUtil.isEmpty(refResource)) {
  151.             return null;
  152.         }
  153.         if (strategy == RuleConstant.STRATEGY_RELATE) {
  154.             //关联资源的ClusterNode
  155.             return ClusterBuilderSlot.getClusterNode(refResource);
  156.         }
  157.         if (strategy == RuleConstant.STRATEGY_CHAIN) {
  158.             if (!refResource.equals(context.getName())) {
  159.                 return null;
  160.             }
  161.             return node;
  162.         }
  163.         //No node.
  164.         return null;
  165.     }
  166.    
  167.     private static boolean filterOrigin(String origin) {
  168.         // Origin cannot be `default` or `other`.
  169.         return !RuleConstant.LIMIT_APP_DEFAULT.equals(origin) && !RuleConstant.LIMIT_APP_OTHER.equals(origin);
  170.     }
  171.     ...
  172. }
复制代码
情形三:limitApp值为other且origin与FlowRule.getResource()不同
  1. public class FlowRuleManager {
  2.     //维护每个资源的流控规则列表,key是资源名称,value是资源对应的规则
  3.     private static volatile Map<String, List<FlowRule>> flowRules = new HashMap<>();
  4.     //饿汉式单例模式实例化流控规则的监听器对象
  5.     private static final FlowPropertyListener LISTENER = new FlowPropertyListener();
  6.     //监听器对象的管理器
  7.     private static SentinelProperty<List<FlowRule>> currentProperty = new DynamicSentinelProperty<List<FlowRule>>();
  8.     ...
  9.     static {
  10.         //将流控规则监听器注册到监听器管理器中
  11.         currentProperty.addListener(LISTENER);
  12.         startMetricTimerListener();
  13.     }
  14.    
  15.     //Load FlowRules, former rules will be replaced.
  16.     //加载流控规则
  17.     public static void loadRules(List<FlowRule> rules) {
  18.         //通知监听器管理器中的每一个监听器,规则已发生变化,需要重新加载规则配置
  19.         //其实就是更新FlowRuleManager规则管理器中的流控规则列表flowRules
  20.         currentProperty.updateValue(rules);
  21.     }
  22.    
  23.     private static final class FlowPropertyListener implements PropertyListener<List<FlowRule>> {
  24.         @Override
  25.         public synchronized void configUpdate(List<FlowRule> value) {
  26.             Map<String, List<FlowRule>> rules = FlowRuleUtil.buildFlowRuleMap(value);
  27.             if (rules != null) {
  28.                 flowRules = rules;
  29.             }
  30.             RecordLog.info("[FlowRuleManager] Flow rules received: {}", rules);
  31.         }
  32.         
  33.         @Override
  34.         public synchronized void configLoad(List<FlowRule> conf) {
  35.             Map<String, List<FlowRule>> rules = FlowRuleUtil.buildFlowRuleMap(conf);
  36.             if (rules != null) {
  37.                 flowRules = rules;
  38.             }
  39.             RecordLog.info("[FlowRuleManager] Flow rules loaded: {}", rules);
  40.         }
  41.     }
  42.     ...
  43. }
  44. public final class FlowRuleUtil {
  45.     private static final Function<FlowRule, String> extractResource = new Function<FlowRule, String>() {
  46.         @Override
  47.         public String apply(FlowRule rule) {
  48.             return rule.getResource();
  49.         }
  50.     };
  51.     ...
  52.     //Build the flow rule map from raw list of flow rules, grouping by provided group function.
  53.     public static <K> Map<K, List<FlowRule>> buildFlowRuleMap(List<FlowRule> list, Function<FlowRule, K> groupFunction, Predicate<FlowRule> filter, boolean shouldSort) {
  54.         Map<K, List<FlowRule>> newRuleMap = new ConcurrentHashMap<>();
  55.         if (list == null || list.isEmpty()) {
  56.             return newRuleMap;
  57.         }
  58.         Map<K, Set<FlowRule>> tmpMap = new ConcurrentHashMap<>();
  59.         for (FlowRule rule : list) {
  60.             ...
  61.             //获取[流控效果]流量整形控制器TrafficShapingController
  62.             TrafficShapingController rater = generateRater(rule);
  63.             rule.setRater(rater);
  64.             //获取资源名
  65.             K key = groupFunction.apply(rule);
  66.             if (key == null) {
  67.                 continue;
  68.             }
  69.             //获取资源名对应的流控规则列表
  70.             Set<FlowRule> flowRules = tmpMap.get(key);
  71.             //将规则放到Map里,和当前资源绑定
  72.             if (flowRules == null) {
  73.                 // Use hash set here to remove duplicate rules.
  74.                 flowRules = new HashSet<>();
  75.                 tmpMap.put(key, flowRules);
  76.             }
  77.             flowRules.add(rule);
  78.         }
  79.         Comparator<FlowRule> comparator = new FlowRuleComparator();
  80.         for (Entry<K, Set<FlowRule>> entries : tmpMap.entrySet()) {
  81.             List<FlowRule> rules = new ArrayList<>(entries.getValue());
  82.             if (shouldSort) {
  83.                 //Sort the rules.
  84.                 Collections.sort(rules, comparator);
  85.             }
  86.             newRuleMap.put(entries.getKey(), rules);
  87.         }
  88.         return newRuleMap;
  89.     }
  90.    
  91.     private static TrafficShapingController generateRater(/*@Valid*/ FlowRule rule) {
  92.         //判断只有当阈值类型为QPS时才生效
  93.         if (rule.getGrade() == RuleConstant.FLOW_GRADE_QPS) {
  94.             //根据流控效果选择不同的流量整形控制器TrafficShapingController
  95.             switch (rule.getControlBehavior()) {
  96.                 case RuleConstant.CONTROL_BEHAVIOR_WARM_UP:
  97.                     //Warm Up预热模式——冷启动模式
  98.                     return new WarmUpController(rule.getCount(), rule.getWarmUpPeriodSec(), ColdFactorProperty.coldFactor);
  99.                 case RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER:
  100.                     //排队等待模式
  101.                     return new RateLimiterController(rule.getMaxQueueingTimeMs(), rule.getCount());
  102.                 case RuleConstant.CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER:
  103.                     //Warm Up + 排队等待模式
  104.                     return new WarmUpRateLimiterController(rule.getCount(), rule.getWarmUpPeriodSec(), rule.getMaxQueueingTimeMs(), ColdFactorProperty.coldFactor);
  105.                 case RuleConstant.CONTROL_BEHAVIOR_DEFAULT:
  106.                     //快速失败模式——Default默认模式
  107.                 default:
  108.                     // Default mode or unknown mode: default traffic shaping controller (fast-reject).
  109.             }
  110.         }
  111.         //默认模式:快速失败用的是DefaultController
  112.         return new DefaultController(rule.getCount(), rule.getGrade());
  113.     }
  114.     ...
  115. }
复制代码
问题二:如何判断阈值类型是QPS还是线程
FlowRule规则类里有个名为grade的字段,代表着阈值类型。所以在初始化DefaultController时就会传入流控规则FlowRule的grade值,这样在DefaultController的avgUsedTokens()方法中,就可以根据grade字段的值判断出阈值类型是QPS还是线程数了。
 
问题三:其中的入参prioritized的作用是什么
DefaultController的canPass()的入参prioritized表示是否对请求设置优先级。当prioritized为true时,表示该请求具有较高优先级的请求。当prioritized为false时,表示该请求是普通请求。而高优先级的请求需要尽量保证其可以通过限流检查。不过一般情况下,prioritized的值默认为false,除非手动指定为true,毕竟限流的目的是不想让超出的流量通过。
 
(3)流控模式中的关联模式和链路模式说明
一.关联模式
关联流控模式中,可以将两个资源进行关联。当某个资源的流量超限时,可以触发其他资源的流控规则。
 
比如用户下单购物时会涉及下单资源和支付资源,如果支付资源达到流控阈值,那么应该要同时禁止下单,也就是通过支付资源来关联到下单资源。
 
注意:如果采取关联模式,那么设置的QPS阈值是被关联者的,而非关联者的。在如下图示中配置了QPS的阈值为3,这是针对testPay资源设置的,而不是针对testOrder资源设置的。也就是testOrder被流控的时机就是当testPay的QPS达到3的时候,3并不是testOrder所访问的次数,而是testPay这个接口被访问的次数。
2.png
二.链路模式
一个资源可能会被多个业务链路调用,不同的业务链路需要进行不同的流控,这时就可以使用链路模式。
 
下图便为testTrace资源创建了一条链路模式的流控规则,规则为QPS限制到1 ,且链路入口资源为/trace/test2。
 
这意味着:/trace/test1链路可以随便访问testTrace资源,不受任何限制。/trace/test2链路访问testTrace资源时会限制QPS为1,超出限制被流控。
3.png
 
3.FlowSlot实现流控规则中排队等待效果的原理
(1)实现排队等待流控效果的普通漏桶算法介绍
(2)RateLimiterController如何实现排队等待效果
(3)RateLimiterController如何判断是否超出阈值
(4)RateLimiterController如何实现排队等待
(5)RateLimiterController实现的漏桶算法与普通漏桶算法的区别
(6)RateLimiterController流控存在的问题
 
(1)实现排队等待流控效果的普通漏桶算法介绍
一.漏桶算法的基本原理
漏桶算法的核心思想是以固定速率流出。
 
假设有一个水桶,水桶底上有几个孔洞。因为孔洞个数和孔洞大小是固定的,因此水从水桶流出的速度是固定的。那么就会有以下两种情况:
 
情况一:往水桶注水的速度小于等于水从孔洞流出的速度,那么水桶中将不会有剩余的水,因为"消费大于等于生产"。
 
情况二:往水桶注水的速度大于水从孔洞流出的速度,那么随着时间推移,水桶会被装满,水会溢出,因为"生产大于消费"。
 
在请求 / 响应场景中,水桶可以被理解为系统处理请求的能力。水对应成请求,水桶对应成一个有限的缓冲区(请求队列)用于存储请求。那么水桶的容量就代表了系统能够处理的最大并发请求数,当水桶满时(请求队列达到上限),新请求将被拒绝,从而实现流量控制。
 
二.漏桶算法的处理流程
步骤一:当新的请求到达时,会将新的请求放入缓冲区(请求队列)中,类似于往水桶里注水。
 
步骤二:系统会以固定的速度处理缓冲区中的请求,类似于水从窟窿中以固定的速度流出,比如开启一个后台线程定时以固定的速度从缓冲区中取出请求然后进行分发处理。
 
步骤三:如果缓冲区已满,则新的请求将被拒绝或丢弃,类似于水溢出。
 
三.漏桶算法的主要特点
特点一:固定速率
水从桶底的孔洞中以固定速率流出,类似于网络中以固定速率发送数据包。但写入速度不固定,也就是请求不是匀速产生的。相当于生产者生产消息不固定,消费者消费消息是匀速消费的。
 
特点二:有限容量
桶的容量有限,当桶满时,新到达的水会溢出,即拒绝超过容量的请求。
 
特点三:先进先出(FIFO)
水按照先进先出的顺序从桶中流出,类似于请求的处理顺序。
 
四.漏桶算法的基本实现
应用场景一:假设有一个视频上传服务,为了确保服务器稳定,希望限制用户在1分钟内最多只能上传5个视频。此时可以使用漏桶算法,将每个视频上传请求视为一个"水滴"。桶的容量设为5个水滴,出水速率设为每分钟5个水滴。当用户上传速度超过限制时,多余的请求将被拒绝。
 
应用场景二:假设有一个向用户发送电子邮件的后台任务,为了确保邮件发送系统的稳定性,希望限制每秒钟最多发送10封邮件。此时可以使用漏桶算法来限制消费MQ的处理速率,将桶的容量设为10个水滴,出水速率设为每秒钟10个水滴。这样,邮件发送系统每秒最多只会处理10封电子邮件。
 
漏桶算法的代码实现如下:
  1. @Spi(order = Constants.ORDER_FLOW_SLOT)
  2. public class FlowSlot extends AbstractLinkedProcessorSlot<DefaultNode> {
  3.     private final FlowRuleChecker checker;
  4.     private final Function<String, Collection<FlowRule>> ruleProvider = new Function<String, Collection<FlowRule>>() {
  5.         @Override
  6.         public Collection<FlowRule> apply(String resource) {
  7.             //Flow rule map should not be null.
  8.             Map<String, List<FlowRule>> flowRules = FlowRuleManager.getFlowRuleMap();
  9.             return flowRules.get(resource);
  10.         }
  11.     };
  12.     ...
  13.     @Override
  14.     public void entry(Context context, ResourceWrapper resourceWrapper, DefaultNode node, int count, boolean prioritized, Object... args) throws Throwable {
  15.         //检查流控规则  
  16.         checkFlow(resourceWrapper, context, node, count, prioritized);
  17.         fireEntry(context, resourceWrapper, node, count, prioritized, args);
  18.     }
  19.    
  20.     void checkFlow(ResourceWrapper resource, Context context, DefaultNode node, int count, boolean prioritized) throws BlockException {
  21.         //调用规则检查器FlowRuleChecker的checkFlow()方法进行检查
  22.         checker.checkFlow(ruleProvider, resource, context, node, count, prioritized);
  23.     }
  24.    
  25.     @Override
  26.     public void exit(Context context, ResourceWrapper resourceWrapper, int count, Object... args) {
  27.         fireExit(context, resourceWrapper, count, args);
  28.     }
  29. }
  30. //Rule checker for flow control rules.
  31. public class FlowRuleChecker {
  32.     public void checkFlow(Function<String, Collection<FlowRule>> ruleProvider, ResourceWrapper resource, Context context, DefaultNode node, int count, boolean prioritized) throws BlockException {
  33.         if (ruleProvider == null || resource == null) {
  34.             return;
  35.         }
  36.         //从Map中获取resource资源对应的流控规则列表
  37.         Collection<FlowRule> rules = ruleProvider.apply(resource.getName());
  38.         if (rules != null) {
  39.             //循环遍历每一个流控规则
  40.             for (FlowRule rule : rules) {
  41.                 //调用canPassCheck方法进行流控规则验证,判断此次请求是否命中针对resource资源配置的流控规则
  42.                 if (!canPassCheck(rule, context, node, count, prioritized)) {
  43.                     throw new FlowException(rule.getLimitApp(), rule);
  44.                 }
  45.             }
  46.         }
  47.     }
  48.    
  49.     public boolean canPassCheck(FlowRule rule, Context context, DefaultNode node, int acquireCount) {
  50.         return canPassCheck(rule, context, node, acquireCount, false);
  51.     }
  52.    
  53.     public boolean canPassCheck(FlowRule rule, Context context, DefaultNode node, int acquireCount, boolean prioritized) {
  54.         //参数校验
  55.         String limitApp = rule.getLimitApp();
  56.         if (limitApp == null) {
  57.             return true;
  58.         }
  59.         //如果是集群模式,则执行passClusterCheck()方法
  60.         if (rule.isClusterMode()) {
  61.             return passClusterCheck(rule, context, node, acquireCount, prioritized);
  62.         }
  63.         //如果是单机模式,则执行passLocalCheck()方法
  64.         return passLocalCheck(rule, context, node, acquireCount, prioritized);
  65.     }
  66.    
  67.     private static boolean passLocalCheck(FlowRule rule, Context context, DefaultNode node, int acquireCount, boolean prioritized) {
  68.         //选择Node作为限流计算的依据
  69.         Node selectedNode = selectNodeByRequesterAndStrategy(rule, context, node);
  70.         if (selectedNode == null) {
  71.             return true;
  72.         }
  73.         //先通过FlowRule.getRater()方法获取流控规则对应的流量整形控制器
  74.         //然后调用TrafficShapingController.canPass()方法对请求进行检查
  75.         return rule.getRater().canPass(selectedNode, acquireCount, prioritized);
  76.     }
  77.     ...
  78. }
  79. //Default throttling controller (immediately reject strategy).
  80. public class DefaultController implements TrafficShapingController {
  81.     private static final int DEFAULT_AVG_USED_TOKENS = 0;
  82.     private double count;
  83.     private int grade;
  84.    
  85.     public DefaultController(double count, int grade) {
  86.         this.count = count;
  87.         this.grade = grade;
  88.     }
  89.    
  90.     @Override
  91.     public boolean canPass(Node node, int acquireCount) {
  92.         return canPass(node, acquireCount, false);
  93.     }
  94.    
  95.     @Override
  96.     public boolean canPass(Node node, int acquireCount, boolean prioritized) {
  97.         //获取当前请求数
  98.         int curCount = avgUsedTokens(node);
  99.         //如果当前请求数 + 1超出阈值,那么返回失败
  100.         if (curCount + acquireCount > count) {
  101.             //进行优先级逻辑处理
  102.             if (prioritized && grade == RuleConstant.FLOW_GRADE_QPS) {
  103.                 long currentTime;
  104.                 long waitInMs;
  105.                 currentTime = TimeUtil.currentTimeMillis();
  106.                 waitInMs = node.tryOccupyNext(currentTime, acquireCount, count);
  107.                 if (waitInMs < OccupyTimeoutProperty.getOccupyTimeout()) {
  108.                     node.addWaitingRequest(currentTime + waitInMs, acquireCount);
  109.                     node.addOccupiedPass(acquireCount);
  110.                     sleep(waitInMs);
  111.                     //PriorityWaitException indicates that the request will pass after waiting for {@link @waitInMs}.
  112.                     throw new PriorityWaitException(waitInMs);
  113.                 }
  114.             }
  115.             return false;
  116.         }
  117.         //如果当前请求数+1没有超出阈值,则返回成功
  118.         return true;
  119.     }
  120.    
  121.     private int avgUsedTokens(Node node) {
  122.         if (node == null) {
  123.             return DEFAULT_AVG_USED_TOKENS;
  124.         }
  125.         return grade == RuleConstant.FLOW_GRADE_THREAD ? node.curThreadNum() : (int)(node.passQps());
  126.     }
  127.    
  128.     private void sleep(long timeMillis) {
  129.         try {
  130.             Thread.sleep(timeMillis);
  131.         } catch (InterruptedException e) {
  132.             //Ignore.
  133.         }
  134.     }
  135. }
复制代码
流程图如下:
4.png
(2)RateLimiterController如何实现排队等待效果
当流控规则中指定的流控效果是排队等待时,对应的流量整形控制器是RateLimiterController。
 
当调用FlowSlot的entry()方法对请求进行流控规则验证时,最终会调用RateLimiterController的canPass()方法来对请求进行检查。
 
RateLimiterController实现排队等待的效果时使用了漏桶算法。既然使用了漏桶算法,那么就一定包含如下字段:
字段一:count,表示QPS阈值,即QPS超出多少后会进行限流。
字段二:latestPassedTime,表示最近允许请求通过的时间。有了这个参数,就能计算出当前请求最早的预期通过时间。
字段三:maxQueueingTimeMs,表示排队时的最大等待时间。
 
(3)RateLimiterController如何判断是否超出阈值
在RateLimiterController的canPass()方法中,为了判断是否超出QPS阈值,通过原子类变量latestPassedTime简化成单线程让请求先后通过的处理模型。为了尽量让业务不受Sentinel影响,采用预估请求的被处理时间点的方式。也就是无需等前面的请求完全被处理完,才确定后面的请求被处理的时间。因为在普通的漏桶算法中,是处理完一个请求,才从漏桶取出水滴。而RateLimiterController的漏桶算法,则是假设请求已经被通过了。
 
具体的判断逻辑如下:首先获取系统的当前时间currentTime。然后计算在满足流控规则中限制的QPS阈值count的情况下,先后的两个请求被允许通过时的最小时间间隔costTime。接着计算当前请求最早的预期通过时间expectedTime,也就是此次请求预计会在几时几分几秒内通过。最后比较expectedTime和currentTime就可知当前请求是否允许通过了。
 
一.如果expectedTime小于等于currentTime
也就是当前请求最早的预期通过时间比系统当前时间小。如果在此时(currentTime)通过当前请求,则当前请求的通过时间就比它最早的预期通过时间(expectedTime)要晚,即当前请求和最近通过的请求的时间间隔变大了,所以此时不会超QPS阈值。于是返回true允许通过,同时更新最近允许请求通过的时间戳为当前时间。
 
二.如果expectedTime大于currentTime
也就是当前请求最早的预期通过时间比系统当前时间大。如果在此时(currentTime)通过当前请求,则当前请求的通过时间就比它最早的预期通过时间(expectedTime)要早,即当前请求和最近通过的请求的时间间隔变小了,比最小间隔时间costTime还小,所以此时必然会超QPS阈值。因此返回进行等待或者返回false不允许通过,等待的最小时间就是:最近通过请求的时间 + 先后两个请求允许通过时的最小间隔时间 - 当前时间。
 
需要注意:Sentinel流量控制的漏桶算法,只能限制在costTime内的流量激增,限制不了costTime外的流量激增。比如系统启动完一瞬间就涌入大量并发请求,此时的流量激增限制不了。又比如系统处理完正常流量的最后一个请求,隔了costTime+的时间后,突然涌入超QPS阈值的并发请求,此时也限制不了这种情况的流量激增。但如果系统处理完正常流量的最后一个请求,隔了costTime-的时间后,突然涌入超QPS阈值的并发请求,此时则可以限制这种情况的流量激增。
[code]public class RateLimiterController implements TrafficShapingController {    //排队等待的意思是超出阈值后等待一段时间,maxQueueingTimeMs就是请求在队列中的最大等待时间    private final int maxQueueingTimeMs;    //流控规则中限制QPS的阈值,也就是QPS超出多少后会进行限制    private final double count;    //最近允许一个请求通过的时间,每次请求通过后就会更新此时间,可以根据该时间计算出当前请求最早的预期通过时间    //注意:Sentinel是在业务前面的,尽量不要让业务受到Sentinel的影响,所以不需要等请求完全被处理完,才确定请求被通过的时间    private final AtomicLong latestPassedTime = new AtomicLong(-1);    public RateLimiterController(int timeOut, double count) {        this.maxQueueingTimeMs = timeOut;        this.count = count;    }        @Override    public boolean canPass(Node node, int acquireCount) {        return canPass(node, acquireCount, false);    }        @Override    public boolean canPass(Node node, int acquireCount, boolean prioritized) {        //Pass when acquire count is less or equal than 0.        //acquireCount代表每次从桶底流出多少个请求        //如果acquireCount小于等于0,则表示无需限流直接通过,不过acquireCount一般默认是1        if (acquireCount

相关推荐

您需要登录后才可以回帖 登录 | 立即注册