1. 序言

Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。

丰富的应用场景: Sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景,例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、实时熔断下游不可用应用等。

完备的实时监控: Sentinel 同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机器秒级数据,甚至 500 台以下规模的集群的汇总运行情况。

广泛的开源生态: Sentinel 提供开箱即用的与其它开源框架/库的整合模块,例如与 Spring Cloud、Dubbo、gRPC 的整合。您只需要引入相应的依赖并进行简单的配置即可快速地接入 Sentinel。

完善的 SPI 扩展点: Sentinel 提供简单易用、完善的 SPI 扩展点。您可以通过实现扩展点,快速的定制逻辑。例如定制规则管理、适配数据源等。

官方文档

2. 工程搭建

2.1. pom

1
2
3
4
5
<!--引入sentinel starter 里面定义好了web 和 注解的方式-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

2.2. 配置

引入则自动配置好了web拦截相关的,即我们之前自己配置的web拦截器识别路径为资源,这里配置的更为详细,所以是不是只用web流控的也可以引入这个然后注入配置呢?哈哈

大概看一下这个配置类的内容
1
可以看见主要就是做web相关的配置了

此外还配置了应用中的切面SentinelResourceRestTemplate的自动配置com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration

这样,我们就引入了sentinel了,cloud工程就是好啊,各种配置看起来就高端

至于流控规则的配置,可以将我们sentinel/数据库持久化篇的相关引用进来,做成nacos配置,sentinel-dashboard控制面板维护。这里就先不配置了。
总之,目前就是差一个FlowManager的配置写入的问题,

PS:官方给的示例表明,配置还可以做成配置文件存在classpath下

1

2.3. openfeign配置

2.3.1. pom

需要先引入spring-cloud-starter-openfeign,用feign的话当然要引入了

2.3.2. 配置

配置文件中直接开启即可,不开启hystrix

1
feign.sentinel.enabled=true

sentinel 对 feign的降级原生支持,可以无缝替换hystrix,应用层面无感知

2.4. restTemplate配置

只需要在配置上增加@SentinelRestTemplate即可

1
2
3
4
5
6
7
8
9
@Configuration
public class RestTemplateConfiguration {

@Bean
@SentinelRestTemplate(urlCleanerClass = UrlCleaner.class, urlCleaner = "clean")
public RestTemplate urlCleanedRestTemplate() {
return new RestTemplate();
}
}

2.5. 动态数据源

动态数据源

指定nacos的配置,这个是方便了,基本都定义好了,而且支持多种数据源
(看来这才是正房,离开了springcloudalibaba的sentinel确是有点被遗弃的感觉)

1
2
3
4
spring.cloud.sentinel.datasource.ds2.nacos.data-id=test-transport-flow-rules
spring.cloud.sentinel.datasource.ds2.nacos.group-id=SENTINEL_GROUP
spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
spring.cloud.sentinel.datasource.ds2.nacos.rule-type=flow

需要注意的是这里的配置如果用sentinel-dashboard管理的话注意data-id和group-id的格式

配置了nacos作为数据源的话还需要引入nacos-datasource依赖

1
2
3
4
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

这样就可以了

  • 写一个接口测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Autowired
    HelloFeign helloFeign;
    @GetMapping("/hello/feign")
    public Object helloOpenFeign() throws InterruptedException {
    System.out.println("hello");
    Object hello = helloFeign.hello();
    Thread.sleep(2000);
    return hello;
    }
  • sentinel-dashboard新建一个流控规则(有延迟)

    rule

    注意此处最前面和webmvc的拦截器模式是一致的,是有/的,

  • Jmeter测试

    测试

    修改流控规则QPS=8再测试,没有问题
    修改测试