Sentinel笔记-黑白名单限流+热点限流
Sentinel 中的黑白名单限流并不难理解,如果配置了黑名单,且请求来源存在黑名单中,则拦截(拒绝)请求,如果配置了白名单,且请求来源存在白名单中则放行。Sentinel 不支持一个黑白名单规则同时配置黑名单和白名单,因此不存优先级的问题。
如果请求中没有Origin,则授权规则限流无效。
AuthorityRuleChecker
AuthorityRuleChecker 负责实现黑白名单的过滤逻辑,其 passCheck 方法源码如下:
static boolean passCheck(AuthorityRule rule, Context context) { // 获取来源 String requester = context.getOrigin(); // 来源为空,或者来源等于规则配置的 limitApp 则拦截请求 if (StringUtil.isEmpty(requester) || StringUtil.isEmpty(rule.getLimitApp())) { return true; } // 字符串查找,这一步起到快速过滤的作用,提升性能 int pos = rule.getLimitApp().indexOf(requester); boolean contain = pos > -1; // 存在才精确匹配 if (contain) { boolean exactlyMatch = false; // 分隔数组 String[] appArray = rule.getLimitApp().split(","); for (String app : appArray) { if (requester.equals(app)) { // 标志设置为 true exactlyMatch = true; break; } } contain = exactlyMatch; } // 策略 int strategy = rule.getStrategy(); // 如果是黑名单,且来源存在规则配置的黑名单中 if (strategy == RuleConstant.AUTHORITY_BLACK && contain) { return false; } // 如果是白名单,且来源不存在规则配置的白名单中 if (strategy == RuleConstant.AUTHORITY_WHITE && !contain) { return false; } return true; }