概述

介绍

随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。

Sentinel 具有以下特征:

  • 丰富的应用场景:Sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景,例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、集群流量控制、实时熔断下游不可用应用等。
  • 完备的实时监控:Sentinel 同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机器秒级数据,甚至 500 台以下规模的集群的汇总运行情况。
  • 广泛的开源生态:Sentinel 提供开箱即用的与其它开源框架/库的整合模块,例如与 Spring Cloud、Dubbo、gRPC 的整合。您只需要引入相应的依赖并进行简单的配置即可快速地接入 Sentinel。
  • 完善的 SPI 扩展点:Sentinel 提供简单易用、完善的 SPI 扩展接口。您可以通过实现扩展接口来快速地定制逻辑。例如定制规则管理、适配动态数据源等。

使用

引入包

1
2
3
4
5
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.6.3</version>
</dependency>

引入资源

把需要控制流量的代码用 Sentinel API SphU.entry(“run”) 和 entry.exit() 包围起来即可。在下面的例子中,我们将 System.out.println(“hello wolrd”); 作为资源,用 API 包围起来。参考代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private void entry(int n){
Entry entry = null;
try {
logger.info("run"+n);
entry = SphU.entry("run");
//Thread.sleep((long)(200*1000*Math.random()));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.info("run end"+n);
} catch (BlockException e) {
logger.info("限流:{}", n);
longAdder.increment();
//logger.info("异常", e);
} finally {
if (entry != null ) {
entry.exit();
}
}
}

定义限流规则

通过规则来指定允许该资源通过的请求次数,例如下面的代码定义了资源 run 每秒最多只能通过 3 个请求。

1
2
3
4
5
6
7
8
9
private void initFlowQpsRule() {
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule("run");
rule.setCount(3);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setLimitApp("default");
rules.add(rule);
FlowRuleManager.loadRules(rules);
}

并发测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void main(String[] args) throws InterruptedException {
int threadN = 100;
SentinelTest sentinelTest = new SentinelTest();
sentinelTest.initFlowQpsRule();
ExecutorService executors = Executors.newFixedThreadPool(5);
CountDownLatch countDownLatch = new CountDownLatch(threadN);
List<Callable<Boolean>> runnables = new ArrayList<>();
for (int a=0; a<threadN; a++){
Integer i = a;
runnables.add(()->{sentinelTest.entry(i);
countDownLatch.countDown();
return true;});
}
executors.invokeAll(runnables);
logger.info("等待");
countDownLatch.await();
logger.info("结束 {}", longAdder.intValue());
}

检查效果

Demo 运行之后,我们可以在日志 ~/logs/csp/${appName}-metrics.log.xxx 里看到下面的输出:

1
2
3
4
5
6
7
|--timestamp-|------date time----|-resource-|p |block|s |e|rt
1529998904000|2018-06-26 15:41:44|run|20|0 |20|0|0
1529998905000|2018-06-26 15:41:45|run|20|5579 |20|0|728
1529998906000|2018-06-26 15:41:46|run|20|15698|20|0|0
1529998907000|2018-06-26 15:41:47|run|20|19262|20|0|0
1529998908000|2018-06-26 15:41:48|run|20|19502|20|0|0
1529998909000|2018-06-26 15:41:49|run|20|18386|20|0|0

其中 p 代表通过的请求, block 代表被阻止的请求, s 代表成功执行完成的请求个数, e 代表用户自定义的异常, rt 代表平均响应时长。

可以看到,这个程序每秒稳定输出 “hello world” 20 次,和规则中预先设定的阈值是一样的。

更详细的说明可以参考: 如何使用

更多的例子可以参考: Sentinel Examples

启动 Sentinel 控制台

您可以参考 Sentinel 控制台文档 启动控制台,可以实时监控各个资源的运行情况,并且可以实时地修改限流规则。