1. Sentinel 是什么?
随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
Sentinel 具有以下特征:
- 丰富的应用场景:Sentinel 承接了阿里巴巴近10年的双十一大促流量的核心场景,例如秒杀、消息削峰填谷、集群流量控制、实时熔断下游不可用应用等。
- 完备的实时监控:Sentinel 同时提供实时的监控功能。你可以在控制台中看到接入应用的单台机器秒级数据,甚至 500 台以下规模的集群的汇总运行情况。
- 广泛的开源生态:Sentinel 提供开箱即用的与其它开源框架/库的整合模块,例如与 Spring Cloud、Dubbo、gRPC 的整合。只需要引入相应的依赖并进行简单的配置即可快速地接入 Sentinel。
- 完善的SPI扩展点:Sentinel 提供简单易用、完善的 SPI 扩展接口。您可以通过实现扩展接口来快速地定制逻辑。例如定制规则管理、适配动态数据源等。
Sentinel 的主要特性:
![dc962ab52882e1889004eecfcefe4039.png](https://i-blog.csdnimg.cn/blog_migrate/33015aab8010de466271c0b21c8b08a8.jpeg)
Sentinel 的开源生态:
![d5d1f3bf2d5a127ecafbde6c48194157.png](https://i-blog.csdnimg.cn/blog_migrate/cf5637a847a4f4ead90c0e4d732619dc.jpeg)
Sentinel 分为两个部分:
- 核心库(Java 客户端)不依赖任何框架/库,能够运行于所有 Java 运行时环境,同时对 Dubbo / Spring Cloud 等框架也有较好的支持。
- 控制台(Dashboard)基于 Spring Boot 开发,打包后可以直接运行,不需要额外的 Tomcat 等应用容器。
2. Sentinel 快速开始
首先,引入 Sentinel 依赖
com.alibaba.csp sentinel-core 1.7.1
接着,定义资源
资源 是 Sentinel 中的核心概念之一。最常用的资源是我们代码中的 Java 方法。 当然,您也可以更灵活的定义你的资源,例如,把需要控制流量的代码用 Sentinel API SphU.entry("HelloWorld") 和 entry.exit() 包围起来即可。在下面的例子中,我们将 System.out.println("hello world"); 作为资源(被保护的逻辑),用 API 包装起来。例如:
try (Entry entry = SphU.entry("HelloWorld")) { // Your business logic here. System.out.println("hello world"); } catch (BlockException e) { // Handle rejected request. e.printStackTrace(); } // try-with-resources auto exit
还可以使用注解定义资源 https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81
例如:
@SentinelResource("HelloWorld") public void helloWorld() { // 资源中的逻辑 System.out.println("hello world"); }
最后,定义规则
接下来,通过流控规则来指定允许该资源通过的请求次数,例如下面的代码定义了资源 HelloWorld 每秒最多只能通过 20 个请求。
private static void initFlowRules(){ List rules = new ArrayList<>(); FlowRule rule = new FlowRule(); rule.setResource("HelloWorld"); rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // Set limit QPS to 20. rule.setCount(20); rules.add(rule); FlowRuleManager.loadRules(rules); }
完成!
完整的代码如下:
pom.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 4 4.0.0 5 6 org.springframework.boot 7 spring-boot-starter-parent 8 2.2.2.RELEASE 9 10 11 com.cjs.example12 sentinel-example13 0.0.1-SNAPSHOT14 sentinel-example15 16 17 1.818 Greenwich.SR419 2.1.0.RELEASE20 21 22 23 24 org.springframework.boot25 spring-boot-starter-actuator26 27 28 org.springframework.boot29 spring-boot-starter-web30 31 32 com.alibaba.cloud33 spring-cloud-starter-alibaba-sentinel34 35 36 37 38 39 40 41 org.springframework.cloud42 spring-cloud-dependencies43 ${spring-cloud.version}44 pom45 import46 47 48 49 com.alibaba.cloud50 spring-cloud-alibaba-dependencies51 ${spring-cloud-alibaba.version}52 pom53 import54 55 56 57 58 59 60 61 org.springframework.boot62 spring-boot-maven-plugin63 64 65 66 67
application.properties
server.port=8084 spring.application.name=sentinel-example spring.cloud.sentinel.transport.dashboard=127.0.0.1:8080