soul从入门到放弃12--sentinel插件

2021-01-28  本文已影响0人  滴流乱转的小胖子

一、前戏

Sentinel 是面向分布式服务架构的高可用流量防护组件,主要以流量为切入点,从限流、流量整形、熔断降级、系统负载保护、热点防护等多个维度来帮助开发者保障微服务的稳定性。

经历了阿里巴巴近10年的双十一大促流量的核心场景考验

二、soul-admin配置

运行Soul-admin,进入管理界面:系统管理 --> 插件管理 --> sentinel ,点击编辑,把它开启

选择器参照divide的匹配方式,让符合条件的http的请求,能被捕获到


image.png

以下配置只是为了更容易出现测试效果,生产环境请勿模仿

image.png

疑问:官方文档描述中有失败降级uri,但是实际规则中并没有发现相关配置,一会从源码一探究竟

degrade count:熔断阈值

whether to open the degrade (1 or 0):是否开启熔断,1开启 0关闭

degrade type:熔断类型、熔断策略,slow call ratio(秒级RT) 、 exception ratio(异常比例)、 exception number strategy(分钟级异常数)

degrade window size:降级窗口期大小,单位s

control behavior: warm up(预热/冷启动方式,流量缓慢增加)、 constant speed queuing (匀速排队)、 preheating uniformly queued

grade count:限流阈值

whether control behavior is enabled (1 or 0):是否开启限流,1开启 0关闭

grade type:限流阈值类型 ,QPS 、number of concurrent threads(当前线程数)

三、soul-Bootstrap

网关层需要引入依赖即可

  <!-- soul sentinel plugin start-->
  <dependency>
      <groupId>org.dromara</groupId>
      <artifactId>soul-spring-boot-starter-plugin-sentinel</artifactId>
       <version>${last.version}</version>
  </dependency>
  <!-- soul sentinel plugin end-->

四、测试

触发降级的三个个条件:满足秒级最大并发量,达到异常比例或者异常数。

所以使用wrk压一下,让流量先上到阈值,便于触发

wrk -t4 -c32 -d10s http://localhost:9195/http/test/findByUserId?userId=2

启动测试一下::http://localhost:9195/http/test/findByUserId?userId=2

熔断的返回值如下:

<pre>{
"code": -103,
"message": "Service invocation exception, or no result is returned!",
"data": null
}</pre>

为了测试效果明显,可以在controller中Thread.sleep(2000);,增加延迟效果

五、源码分析

分析前理解sentinel中两个重要的概念:资源与规则

https://github.com/alibaba/Sentinel/wiki/%E4%B8%BB%E9%A1%B5

根据数据同步机制,会逐条规则的同步/初始化限流、熔断资源

image.png

单条同步创建,最终落地创建/更新资源在SentinelRuleHandle#handlerRule

// 获取sentinel已有规则,过滤掉原有与新增同资源名的规则
List<DegradeRule> degradeRules = DegradeRuleManager.getRules()
        .stream()
        .filter(r -> !r.getResource().equals(getResourceName(ruleData)))
        .collect(Collectors.toList());
        // some code
        // 更新sentinel规则
        DegradeRuleManager.loadRules(degradeRules);

资源名的定义规则

选择器Id_规则名称

ruleData.getSelectorId() + "_" + ruleData.getName();

image.png image.png

六、小结

上一篇下一篇

猜你喜欢

热点阅读