二十一、Sentinel规则之黑白名单规则

很多时候,我们需要根据调用方来限制资源是否通过,这时候可以使用 Sentinel 的黑白名单控制的功能。
黑白名单根据资源的请求来源(origin)限制资源是否通过,若配置白名单则只有请求来源位于白名单内时才可通过;
若配置黑名单则请求来源位于黑名单时不通过,其余的请求通过。

调用方信息通过 ContextUtil.enter(resourceName, origin) 方法中的 origin 参数传入

规则配置

黑白名单规则(AuthorityRule)非常简单,主要有以下配置项:

  • resource:资源名,即限流规则的作用对象
  • limitApp:对应的黑名单/白名单,不同 origin 用 , 分隔,如 appA,appB
  • strategy:限制模式,AUTHORITY_WHITE 为白名单模式,AUTHORITY_BLACK 为黑名单模式,默认为白名单模式

源码

1
2
3
4
public class AuthorityRule extends AbstractRule {
//Mode: 0 for whitelist; 1 for blacklist.
private int strategy = RuleConstant.AUTHORITY_WHITE;
}

实验

这个规则比前面的规则都更加简单,而且更加容易理解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public static void testAuthorityRuleWithWhite() {
ContextUtil.enter("entrance1","App3");
Entry entry = null;
try {
entry = SphU.entry("login");
System.out.println("访问通过!");
} catch (BlockException e) {
System.out.println("访问受限!");
} finally {
if (entry != null) {
entry.exit();
}
}
}

public static void initAuthorityRule() {
List<AuthorityRule> rules = new ArrayList<>();
AuthorityRule rule = new AuthorityRule();
rule.setResource("login");
//配置白名单
rule.setStrategy(RuleConstant.AUTHORITY_WHITE);
rule.setLimitApp("App1,App2");
rules.add(rule);
AuthorityRuleManager.loadRules(rules);
}

上面代码测试结果为:访问受限!

  • 通过Strategy 来设置规则策略,白名单和黑名单。
  • 通过LimitApp 来配置白名单列表或黑名单列表。多个之间使用逗号隔开。

上面的初始化规则在页面显示如下:

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×