Sentinel

x33g5p2x  于2021-11-13 转载在 其他  
字(35.9k)|赞(0)|评价(0)|浏览(435)

资料

Sentinel官方文档

Github地址

介绍

Sentinel 是什么?

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

Sentinel 具有以下特征:

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

Sentinel 的主要特性:

github链接

—句话解释,之前我们讲解过的Hystrix。

Hystrix与Sentinel比较:

Hystrix
需要我们程序员自己手工搭建监控平台
没有一套web界面可以给我们进行更加细粒度化得配置流控、速率控制、服务熔断、服务降级
Sentinel
单独一个组件,可以独立出来。
直接界面化的细粒度统一配置。
约定 > 配置 > 编码

都可以写在代码里面,但是我们本次还是大规模的学习使用配置和注解的方式,尽量少写代码

Sentinel下载安装运行

springcloud官方文档

服务使用中的各种问题:

  • 服务雪崩
  • 服务降级
  • 服务熔断
  • 服务限流

Sentinel 分为两个部分:

  • 核心库(Java 客户端)不依赖任何框架/库,能够运行于所有 Java 运行时环境,同时对 Dubbo / Spring
    Cloud 等框架也有较好的支持。
  • 控制台(Dashboard)基于 Spring Boot 开发,打包后可以直接运行,不需要额外的 Tomcat 等应用容器。

安装步骤:

下载

https://github.com/alibaba/Sentinel/releases

下载到本地sentinel-dashboard-1.7.0.jar

运行命令

前提

Java 8 环境

8080端口不能被占用

命令

java -jar sentinel-dashboard-1.7.0.jar

访问Sentinel管理界面

localhost:8080

登录账号密码均为sentinel

Sentinel初始化监控

启动Nacos8848成功

新建工程 - cloudalibaba-sentinel-service8401

POM

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>cloud_Parent</artifactId>
  7. <groupId>dhy.xpy</groupId>
  8. <version>520.521.finally</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>cloudalibaba-sentinel-service8401</artifactId>
  12. <properties>
  13. <maven.compiler.source>16</maven.compiler.source>
  14. <maven.compiler.target>16</maven.compiler.target>
  15. </properties>
  16. <dependencies>
  17. <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
  18. <groupId>com.dhy.springCloud</groupId>
  19. <artifactId>cloud-api-commons</artifactId>
  20. <version>1.0-SNAPSHOT</version>
  21. </dependency>
  22. <!--SpringCloud ailibaba nacos -->
  23. <dependency>
  24. <groupId>com.alibaba.cloud</groupId>
  25. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
  26. </dependency>
  27. <!--SpringCloud ailibaba sentinel-datasource-nacos 后续做持久化用到-->
  28. <dependency>
  29. <groupId>com.alibaba.csp</groupId>
  30. <artifactId>sentinel-datasource-nacos</artifactId>
  31. </dependency>
  32. <!--SpringCloud ailibaba sentinel -->
  33. <dependency>
  34. <groupId>com.alibaba.cloud</groupId>
  35. <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
  36. </dependency>
  37. <!--openfeign-->
  38. <dependency>
  39. <groupId>org.springframework.cloud</groupId>
  40. <artifactId>spring-cloud-starter-openfeign</artifactId>
  41. </dependency>
  42. <!-- SpringBoot整合Web组件+actuator -->
  43. <dependency>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-starter-web</artifactId>
  46. </dependency>
  47. <dependency>
  48. <groupId>org.springframework.boot</groupId>
  49. <artifactId>spring-boot-starter-actuator</artifactId>
  50. </dependency>
  51. <!--日常通用jar包配置-->
  52. <dependency>
  53. <groupId>org.springframework.boot</groupId>
  54. <artifactId>spring-boot-devtools</artifactId>
  55. <scope>runtime</scope>
  56. <optional>true</optional>
  57. </dependency>
  58. <dependency>
  59. <groupId>cn.hutool</groupId>
  60. <artifactId>hutool-all</artifactId>
  61. <version>4.6.3</version>
  62. </dependency>
  63. <dependency>
  64. <groupId>org.projectlombok</groupId>
  65. <artifactId>lombok</artifactId>
  66. <optional>true</optional>
  67. </dependency>
  68. <dependency>
  69. <groupId>org.springframework.boot</groupId>
  70. <artifactId>spring-boot-starter-test</artifactId>
  71. <scope>test</scope>
  72. </dependency>
  73. </dependencies>
  74. </project>

YML:

  1. server:
  2. port: 8401
  3. spring:
  4. application:
  5. name: cloudalibaba-sentinel-service
  6. cloud:
  7. nacos:
  8. discovery:
  9. server-addr: localhost:8848 #Nacos服务注册中心地址
  10. sentinel:
  11. transport:
  12. dashboard: localhost:8080 #配置Sentinel dashboard地址
  13. #Sentinel会启动一个http server和dashboard进行通信,而这个server默认占用端口是9719
  14. #加入8719端口被占用,会自动+1,直到找到没有被占用的端口为止
  15. port: 8719
  16. management:
  17. endpoints:
  18. web:
  19. exposure:
  20. include: '*'
  21. feign:
  22. sentinel:
  23. enabled: true # 激活Sentinel对Feign的支持

主启动

  1. @EnableDiscoveryClient
  2. @SpringBootApplication
  3. public class Nacos8401
  4. {
  5. public static void main(String[] args) {
  6. SpringApplication.run(Nacos8401.class, args);
  7. }
  8. }

业务类FlowLimitController

  1. import lombok.extern.slf4j.Slf4j;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. @Slf4j
  6. public class FlowLimitController {
  7. @GetMapping("/testA")
  8. public String testA()
  9. {
  10. return "------testA";
  11. }
  12. @GetMapping("/testB")
  13. public String testB()
  14. {
  15. log.info(Thread.currentThread().getName()+"\t"+"...testB");
  16. return "------testB";
  17. }
  18. }

启动Sentinel8080 - java -jar sentinel-dashboard-1.7.0.jar

启动微服务8401

启动8401微服务后查看sentienl控制台

  • 刚启动,空空如也,啥都没有

Sentinel采用的懒加载说明

执行一次访问即可

http://localhost:8401/testA

http://localhost:8401/testB

效果 - sentinel8080正在监控微服务8401

Sentinel流控规则简介

基本介绍

进一步解释说明:

  • 资源名:唯一名称,默认请求路径。
  • 针对来源:Sentinel可以针对调用者进行限流,填写微服务名,默认default(不区分来源)。
  • 阈值类型/单机阈值:
  • QPS(每秒钟的请求数量)︰当调用该API的QPS达到阈值的时候,进行限流。
  • 线程数:当调用该API的线程数达到阈值的时候,进行限流。
  • 是否集群:不需要集群。
  • 流控模式:
  • 直接:API达到限流条件时,直接限流。
  • 关联:当关联的资源达到阈值时,就限流自己。
  • 链路:只记录指定链路上的流量(指定资源从入口资源进来的流量,如果达到阈值,就进行限流)【API级别的针对来源】。
  • 流控效果:
  • 快速失败:直接失败,抛异常。
  • Warm up:根据Code Factor(冷加载因子,默认3)的值,从阈值/codeFactor,经过预热时长,才达到设置的QPS阈值。
  • 排队等待:匀速排队,让请求以匀速的速度通过,阈值类型必须设置为QPS,否则无效。

Sentinel流控-QPS直接失败

直接 -> 快速失败(系统默认)

配置及说明

表示1秒钟内查询1次就是OK,若超过次数1,就直接->快速失败,报默认错误

测试

快速多次点击访问http://localhost:8401/testA

结果

返回页面 Blocked by Sentinel (flow limiting)

源码

com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController

思考

直接调用默认报错信息,技术方面OK,但是,是否应该有我们自己的后续处理?类似有个fallback的兜底方法?

Sentinel流控-线程数直接失败

线程数:当调用该API的线程数达到阈值的时候,进行限流。

例如: 一个请求处理一次,耗时1秒,如果同时有10个线程在一秒内访问这个请求,那么只有第一个请求会得到处理,剩余的请求会被拦截

Sentinel流控-关联

是什么?

  • 当自己关联的资源达到阈值时,就限流自己
  • 当与A关联的资源B达到阀值后,就限流A自己(B惹事,A挂了)

设置testA

当关联资源/testB的QPS阀值超过1时,就限流/testA的Rest访问地址,当关联资源到阈值后限制配置好的资源名。

Postman模拟并发密集访问testB

访问testB成功

postman里新建多线程集合组

将访问地址添加进新新线程组

Run - 大批量线程高并发访问B

Postman运行后,点击访问http://localhost:8401/testA,发现testA挂了

  • 结果Blocked by Sentinel(flow limiting)

Sentinel流控-链路

只记录指定链路上的流量(指定资源从入口资源进来的流量,如果达到阈值,就进行限流)【API级别的针对来源】

Sentinel流控-预热

Warm Up

Warm Up(RuleConstant.CONTROL_BEHAVIOR_WARM_UP)方式,即预热/冷启动方式。当系统长期处于低水位的情况下,当流量突然增加时,直接把系统拉升到高水位可能瞬间把系统压垮。通过"冷启动",让通过的流量缓慢增加,在一定时间内逐渐增加到阈值上限,给冷系统一个预热的时间,避免冷系统被压垮。详细文档可以参考 流量控制 - Warm Up 文档,具体的例子可以参见 WarmUpFlowDemo。

通常冷启动的过程系统允许通过的 QPS 曲线如下图所示:

link

默认coldFactor为3,即请求QPS 从 threshold / 3开始,经预热时长逐渐升至设定的QPS阈值。link

源码 - com.alibaba.csp.sentinel.slots.block.flow.controller.WarmUpController

WarmUp配置

案例,阀值为10+预热时长设置5秒。

系统初始化的阀值为10/ 3约等于3,即阀值刚开始为3;然后过了5秒后阀值才慢慢升高恢复到10

测试

多次快速点击http://localhost:8401/testB - 刚开始不行,后续慢慢OK

应用场景

如:秒杀系统在开启的瞬间,会有很多流量上来,很有可能把系统打死,预热方式就是把为了保护系统,可慢慢的把流量放进来,慢慢的把阀值增长到设置的阀值。

Sentinel流控-排队等待

匀速排队,让请求以均匀的速度通过,阀值类型必须设成QPS,否则无效。

设置:/testA每秒1次请求,超过的话就排队等待,等待的超时时间为20000毫秒。

匀速排队

匀速排队(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)方式会严格控制请求通过的间隔时间,也即是让请求以均匀的速度通过,对应的是漏桶算法。详细文档可以参考 流量控制 - 匀速器模式,具体的例子可以参见 PaceFlowDemo

该方式的作用如下图所示:

这种方式主要用于处理间隔性突发的流量,例如消息队列。想象一下这样的场景,在某一秒有大量的请求到来,而接下来的几秒则处于空闲状态,我们希望系统能够在接下来的空闲期间逐渐处理这些请求,而不是在第一秒直接拒绝多余的请求。

注意:匀速排队模式暂时不支持 QPS > 1000 的场景。

link

源码 - com.alibaba.csp.sentinel.slots.block.flow.controller.RateLimiterController

测试

  • 添加日志记录代码到FlowLimitController的testA方法
  1. @RestController
  2. @Slf4j
  3. public class FlowLimitController {
  4. @GetMapping("/testA")
  5. public String testA()
  6. {
  7. log.info(Thread.currentThread().getName()+"\t"+"...testA");//<----
  8. return "------testA";
  9. }
  10. ...
  11. }

Postman模拟并发密集访问testA。

后台结果

Sentinel降级简介

官方文档

熔断降级概述

除了流量控制以外,对调用链路中不稳定的资源进行熔断降级也是保障高可用的重要措施之一。一个服务常常会调用别的模块,可能是另外的一个远程服务、数据库,或者第三方 API 等。例如,支付的时候,可能需要远程调用银联提供的 API;查询某个商品的价格,可能需要进行数据库查询。然而,这个被依赖服务的稳定性是不能保证的。如果依赖的服务出现了不稳定的情况,请求的响应时间变长,那么调用服务的方法的响应时间也会变长,线程会产生堆积,最终可能耗尽业务自身的线程池,服务本身也变得不可用。

现代微服务架构都是分布式的,由非常多的服务组成。不同服务之间相互调用,组成复杂的调用链路。以上的问题在链路调用中会产生放大的效果。复杂链路上的某一环不稳定,就可能会层层级联,最终导致整个链路都不可用。因此我们需要对不稳定的弱依赖服务调用进行熔断降级,暂时切断不稳定调用,避免局部不稳定因素导致整体的雪崩。熔断降级作为保护自身的手段,通常在客户端(调用端)进行配置。

link

  • RT(平均响应时间,秒级)
  1. 平均响应时间 超出阈值 在时间窗口内通过的请求>=5,两个条件同时满足后触发降级。
  • 窗口期过后关闭断路器。
  1. RT最大4900(更大的需要通过-Dcsp.sentinel.statistic.max.rt=XXXX才能生效)。
  2. 异常比列(秒级)
  1. QPS >= 5且异常比例(秒级统计)超过阈值时,触发降级;时间窗口结束后,关闭降级
  2. 异常数(分钟级)
  • 异常数(分钟统计)超过阈值时,触发降级;时间窗口结束后,关闭降级

Sentinel熔断降级会在调用链路中某个资源出现不稳定状态时(例如调用超时或异常比例升高),对这个资源的调用进行限制,让请求快速失败,避免影响到其它的资源而导致级联错误。

当资源被降级后,在接下来的降级时间窗口之内,对该资源的调用都自动熔断(默认行为是抛出 DegradeException)。

Sentinei的断路器是没有类似Hystrix半开状态的。(Sentinei 1.8.0 已有半开状态)

半开的状态系统自动去检测是否请求有异常,没有异常就关闭断路器恢复使用,有异常则继续打开断路器不可用。

Sentinel降级-RT

是什么?

平均响应时间(DEGRADE_GRADE_RT):当1s内持续进入5个请求,对应时刻的平均响应时间(秒级)均超过阈值( count,以ms为单位),那么在接下的时间窗口(DegradeRule中的timeWindow,以s为单位)之内,对这个方法的调用都会自动地熔断(抛出DegradeException )。注意Sentinel 默认统计的RT上限是4900 ms,超出此阈值的都会算作4900ms,若需要变更此上限可以通过启动配置项-Dcsp.sentinel.statistic.max.rt=xxx来配置。

注意:Sentinel 1.7.0才有平均响应时间(DEGRADE_GRADE_RT),Sentinel 1.8.0的没有这项,取而代之的是慢调用比例 (SLOW_REQUEST_RATIO)。

慢调用比例 (SLOW_REQUEST_RATIO):选择以慢调用比例作为阈值,需要设置允许的慢调用 RT(即最大的响应时间),请求的响应时间大于该值则统计为慢调用。当单位统计时长(statIntervalMs)内请求数目大于设置的最小请求数目,并且慢调用的比例大于阈值,则接下来的熔断时长内请求会自动被熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求响应时间小于设置的慢调用 RT 则结束熔断,若大于设置的慢调用 RT 则会再次被熔断

熔断策略

接下来讲解Sentinel 1.7.0的。

测试

代码

  1. @RestController
  2. @Slf4j
  3. public class FlowLimitController {
  4. ...
  5. @GetMapping("/testD")
  6. public String testD() {
  7. try {
  8. TimeUnit.SECONDS.sleep(1);
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. log.info("testD 测试RT");
  13. }
  14. }

配置

jmeter压测

结论

按照上述配置,永远一秒钟打进来10个线程(大于5个了)调用testD,我们希望200毫秒处理完本次任务,如果超过200毫秒还没处理完,在未来1秒钟的时间窗口内,断路器打开(保险丝跳闸)微服务不可用,保险丝跳闸断电了后续我停止jmeter,没有这么大的访问量了,断路器关闭(保险丝恢复),微服务恢复OK。

1.8+版本的慢调用比例解释

1.调用:一个请求发送到服务器,服务器给与响应,一个响应就是一个调用。
2.RT:响应时间,指系统对请求作出响应的时间。
3.慢调用:当调用的时间(响应的实际时间)>设置的RT的时,这个调用叫做慢调用。
4.慢调用比例:在所以调用中,慢调用占有实际的比例,= 慢调用次数 / 调用次数
5.比例阈值:自己设定的 , 慢调用次数 / 调用次数=比例阈值

统计时长:时间的判断依据
最小请求数:设置的调用最小请求数

状态转换

进入熔断状态判断依据:当统计时常内,实际请求数目大于最小请求数目,慢调用比例> 比例阈值 ,进入熔断状态

②熔断状态:在接下来的熔断时长内请求会自动被熔断

③探测恢复状态:熔断时长结束后进入探测恢复状态

④结束熔断:在探测恢复状态,如果接下来的一个请求响应时间小于设置的慢调用 RT,则结束熔断
否则继续熔断。

例子:

服务器响应时长设置:暂停1秒,所以响应一个请求的时长都大于1秒

熔断条件:

在1000毫秒,也就是1秒内,如果发送到/testD 的请求数数量大于5,并且在这些请求中,所有请求的响应时长(因为比例与阈值为1,所以是所有的请求响应时长)都大于500毫秒,也就是都大于0.5秒的时候,进入熔断状态。

.jmeter测试

①设置测试地址

②设置线程和组

10个线程,在一秒的时间内发送完。

又因为服务器响应时长设置:暂停1秒,所以响应一个请求的时长都大于1秒

综上符合熔断条件,所以当线程开启1秒后,进入熔断状态

③测试:

Ⅰ.开启十个线程

浏览器测试熔断

关闭十个线程,再进行浏览器测试

正常访问

Sentinel降级-异常比例

是什么?

异常比例(DEGRADE_GRADE_EXCEPTION_RATIO):当资源的每秒请求量 >= 5,并且每秒异常总数占通过量的比值超过阈值( DegradeRule中的 count)之后,资源进入降级状态,即在接下的时间窗口( DegradeRule中的timeWindow,以s为单位)之内,对这个方法的调用都会自动地返回。异常比率的阈值范围是[0.0, 1.0],代表0% -100%。

注意,与Sentinel 1.8.0相比,有些不同(Sentinel 1.8.0才有的半开状态),Sentinel 1.8.0的如下:

异常比例 (ERROR_RATIO):当单位统计时长(statIntervalMs)内请求数目大于设置的最小请求数目,并且异常的比例大于阈值,则接下来的熔断时长内请求会自动被熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求成功完成(没有错误)则结束熔断,否则会再次被熔断。异常比率的阈值范围是 [0.0, 1.0],代表 0% - 100%

接下来讲解Sentinel 1.7.0的。

测试

  1. @RestController
  2. @Slf4j
  3. public class FlowLimitController {
  4. ...
  5. @GetMapping("/testD")
  6. public String testD() {
  7. log.info("testD 异常比例");
  8. int age = 10/0;
  9. return "------testD";
  10. }
  11. }

配置

jmeter

结论

按照上述配置,单独访问一次,必然来一次报错一次(int age = 10/0),调一次错一次。

开启jmeter后,直接高并发发送请求,多次调用达到我们的配置条件了。断路器开启(保险丝跳闸),微服务不可用了,不再报错error而是服务降级了。

Sentinel降级-异常数

是什么?

异常数( DEGRADE_GRADF_EXCEPTION_COUNT ):当资源近1分钟的异常数目超过阈值之后会进行熔断。注意由于统计时间窗口是分钟级别的,若timeWindow小于60s,则结束熔断状态后码可能再进入熔断状态。

注意,与Sentinel 1.8.0相比,有些不同(Sentinel 1.8.0才有的半开状态),Sentinel 1.8.0的如下:

异常数 (ERROR_COUNT):当单位统计时长内的异常数目超过阈值之后会自动进行熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求成功完成(没有错误)则结束熔断,否则会再次被熔断。

接下来讲解Sentinel 1.7.0的。

异常数是按照分钟统计的,时间窗口一定要大于等于60秒。

测试

  1. @RestController
  2. @Slf4j
  3. public class FlowLimitController{
  4. ...
  5. @GetMapping("/testE")
  6. public String testE()
  7. {
  8. log.info("testE 测试异常数");
  9. int age = 10/0;
  10. return "------testE 测试异常数";
  11. }
  12. }

配置

访问http://localhost:8401/testE,第一次访问绝对报错,因为除数不能为零,我们看到error窗口,但是达到5次报错后,进入熔断后降级。

Sentinel热点key

基本介绍

官网

官方文档

何为热点?热点即经常访问的数据。很多时候我们希望统计某个热点数据中访问频次最高的 Top K 数据,并对其访问进行限制。比如:

  • 商品 ID 为参数,统计一段时间内最常购买的商品 ID 并进行限制
  • 用户 ID 为参数,针对一段时间内频繁访问的用户 ID 进行限制

热点参数限流会统计传入参数中的热点参数,并根据配置的限流阈值与模式,对包含热点参数的资源调用进行限流。热点参数限流可以看做是一种特殊的流量控制,仅对包含热点参数的资源调用生效。

Sentinel 利用 LRU 策略统计最近最常访问的热点参数,结合令牌桶算法来进行参数级别的流控。热点参数限流支持集群模式。

官网链接

承上启下复习start

兜底方法,分为系统默认和客户自定义,两种

之前的case,限流出问题后,都是用sentinel系统默认的提示: Blocked by Sentinel (flow limiting)

我们能不能自定?类似hystrix,某个方法出问题了,就找对应的兜底降级方法?

结论 - 从HystrixCommand到@SentinelResource

代码

com.alibaba.csp.sentinel.slots.block.BlockException

  1. @RestController
  2. @Slf4j
  3. public class FlowLimitController
  4. {
  5. @GetMapping("/testHotKey")
  6. @SentinelResource(value = "testHotKey",blockHandler/*兜底方法*/ = "deal_testHotKey")
  7. public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
  8. @RequestParam(value = "p2",required = false) String p2) {
  9. //int age = 10/0;
  10. return "------testHotKey";
  11. }
  12. /*兜底方法*/
  13. public String deal_testHotKey (String p1, String p2, BlockException exception) {
  14. return "------deal_testHotKey,o(╥﹏╥)o"; //sentinel系统默认的提示:Blocked by Sentinel (flow limiting)
  15. }
  16. }

配置

写法一:

  • @SentinelResource(value = "testHotKey")
  • 异常打到了前台用户界面看到,不友好

写法二:

  • @SentinelResource(value = "testHotKey", blockHandler ="dealHandler_testHotKey")
  • 方法testHotKey里面第一个参数只要QPS超过每秒1次,马上降级处理
  • 异常用了我们自己定义的兜底方法

测试

error

http://localhost:8401/testHotKey?p1=abc

http://localhost:8401/testHotKey?p1=abc&p2=33

right

http://localhost:8401/testHotKey?p2=abc

因为p1是热点key,p2不是热点key

参考

Sentinel之@SentinelResource注解的使用

上述案例演示了第一个参数p1,当QPS超过1秒1次点击后马上被限流。

参数例外项

  • 普通 - 超过1秒钟一个后,达到阈值1后马上被限流
  • 我们期望p1参数当它是某个特殊值时,它的限流值和平时不一样
  • 特例 - 假如当p1的值等于5时,它的阈值可以达到200

配置

测试

  • right - http://localhost:8401/testHotKey?p1=5
  • error - http://localhost:8401/testHotKey?p1=3

当p1等于5的时候,阈值变为200

当p1不等于5的时候,阈值就是平常的1

前提条件 - 热点参数的注意点,参数必须是基本类型或者String

其它

在方法体抛异常

  1. @RestController
  2. @Slf4j
  3. public class FlowLimitController
  4. {
  5. ...
  6. @GetMapping("/testHotKey")
  7. @SentinelResource(value = "testHotKey",blockHandler/*兜底方法*/ = "deal_testHotKey")
  8. public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
  9. @RequestParam(value = "p2",required = false) String p2) {
  10. int age = 10/0;//<----------------------------会抛异常的地方
  11. return "------testHotKey";
  12. }
  13. /*兜底方法*/
  14. public String deal_testHotKey (String p1, String p2, BlockException exception) {
  15. return "------deal_testHotKey,o(╥﹏╥)o"; //sentinel系统默认的提示:Blocked by Sentinel (flow limiting)
  16. }
  17. }

将会抛出Spring Boot 2的默认异常页面,而不是兜底方法。

  • @SentinelResource 处理的是sentinel控制台配置的违规情况,有blockHandler方法配置的兜底处理;
  • RuntimeException int age =10/0,这个是java运行时报出的运行时异常RunTimeException,@SentinelResource不管

总结 - @SentinelResource主管配置出错,运行出错该走异常走异常

Sentinel系统规则

官方文档

Sentinel 系统自适应限流从整体维度对应用入口流量进行控制,结合应用的 Load、CPU 使用率、总体平均 RT、入口 QPS 和并发线程数等几个维度的监控指标,通过自适应的流控策略,让系统的入口流量和系统的负载达到一个平衡,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性

系统自适应限流

系统规则

系统保护规则是从应用级别的入口流量进行控制,从单台机器的 load、CPU 使用率、平均 RT、入口 QPS 和并发线程数等几个维度监控应用指标,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。

系统保护规则是应用整体维度的,而不是资源维度的,并且仅对入口流量生效。入口流量指的是进入应用的流量(EntryType.IN),比如 Web 服务或 Dubbo 服务端接收的请求,都属于入口流量。

系统规则支持以下的模式:

  • Load 自适应(仅对 Linux/Unix-like 机器生效):系统的 load1 作为启发指标,进行自适应系统保护。当系统load1 超过设定的启发值,且系统当前的并发线程数超过估算的系统容量时才会触发系统保护(BBR 阶段)。系统容量由系统的maxQps * minRt 估算得出。设定参考值一般是 CPU cores * 2.5。
  • CPU usage(1.5.0+ 版本):当系统 CPU 使用率超过阈值即触发系统保护(取值范围 0.0-1.0),比较灵敏。
  • 平均 RT:当单台机器上所有入口流量的平均 RT 达到阈值即触发系统保护,单位是毫秒。
  • 并发线程数:当单台机器上所有入口流量的并发线程数达到阈值即触发系统保护。
  • 入口 QPS:当单台机器上所有入口流量的 QPS 达到阈值即触发系统保护。

系统规则

SentinelResource配置(上)

按资源名称限流 + 后续处理

启动Nacos成功

启动Sentinel成功

Module - cloudalibaba-sentinel-service8401

  1. import com.alibaba.csp.sentinel.annotation.SentinelResource;
  2. import com.alibaba.csp.sentinel.slots.block.BlockException;
  3. import com.atguigu.springcloud.alibaba.myhandler.CustomerBlockHandler;
  4. import com.atguigu.springcloud.entities.CommonResult;
  5. import com.atguigu.springcloud.entities.Payment;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. @RestController
  9. public class RateLimitController {
  10. @GetMapping("/byResource")
  11. @SentinelResource(value = "byResource",blockHandler = "handleException")
  12. public CommonResult byResource() {
  13. return new CommonResult(200,"按资源名称限流测试OK",new Payment(2020L,"serial001"));
  14. }
  15. public CommonResult handleException(BlockException exception) {
  16. return new CommonResult(444,exception.getClass().getCanonicalName()+"\t 服务不可用");
  17. }
  18. }

配置流控规则

配置步骤

图形配置和代码关系

表示1秒钟内查询次数大于1,就跑到我们自定义的处流,限流

测试

1秒钟点击1下,OK

超过上述,疯狂点击,返回了自己定义的限流处理信息,限流发生

  1. {"code":444, "message":"com.alibaba.csp.sentinel.slots.block.flow.FlowException\t 服务不可用", "data":null}

额外问题

此时关闭问服务8401 -> Sentinel控制台,流控规则消失了,说明流控规则是临时的

按照Url地址限流 + 后续处理

通过访问的URL来限流,会返回Sentinel自带默认的限流处理信息

业务类RateLimitController

  1. @RestController
  2. public class RateLimitController
  3. {
  4. ...
  5. @GetMapping("/rateLimit/byUrl")
  6. @SentinelResource(value = "byUrl")
  7. public CommonResult byUrl()
  8. {
  9. return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002"));
  10. }
  11. }

Sentinel控制台配置

测试

快速点击http://localhost:8401/rateLimit/byUrl

结果 - 会返回Sentinel自带的限流处理结果 Blocked by Sentinel (flow limiting)

上面兜底方案面临的问题

系统默认的,没有体现我们自己的业务要求。

依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观。

每个业务方法都添加—个兜底的,那代码膨胀加剧。

全局统—的处理方法没有体现。

SentinelResource配置(中)

客户自定义限流处理逻辑

自定义限流处理类 - 创建CustomerBlockHandler类用于自定义限流处理逻辑

  1. import com.alibaba.csp.sentinel.slots.block.BlockException;
  2. import com.atguigu.springcloud.entities.CommonResult;
  3. import com.atguigu.springcloud.entities.Payment;
  4. public class CustomerBlockHandler {
  5. public static CommonResult handlerException(BlockException exception) {
  6. return new CommonResult(4444,"按客戶自定义,global handlerException----1");
  7. }
  8. public static CommonResult handlerException2(BlockException exception) {
  9. return new CommonResult(4444,"按客戶自定义,global handlerException----2");
  10. }
  11. }

RateLimitController

  1. @RestController
  2. public class RateLimitController {
  3. ...
  4. @GetMapping("/rateLimit/customerBlockHandler")
  5. @SentinelResource(value = "customerBlockHandler",
  6. blockHandlerClass = CustomerBlockHandler.class,//<-------- 自定义限流处理类
  7. blockHandler = "handlerException2")//<-----------
  8. public CommonResult customerBlockHandler()
  9. {
  10. return new CommonResult(200,"按客戶自定义",new Payment(2020L,"serial003"));
  11. }
  12. }

Sentinel控制台配置

启动微服务后先调用一次 - http://localhost:8401/rateLimit/customerBlockHandler。然后,多次快速刷新http://localhost:8401/rateLimit/customerBlockHandler。刷新后,我们自定义兜底方法的字符串信息就返回到前端。

SentinelResource配置(下)

@SentinelResource 注解

注意:注解方式不支持 private 方法。

@SentinelResource 用于定义资源,并提供可选的异常处理和 fallback 配置项@SentinelResource 注解包含以下属性:

  • value:资源名称,必需项(不能为空)
  • entryType:entry 类型,可选项(默认为 EntryType.OUT
  • blockHandler / blockHandlerClass: blockHandler 对应处理 BlockException 的函数名称,可选项。blockHandler 函数访问范围需要是 public返回类型需要与原方法相匹配,参数类型需要和原方法相匹配并且最后可以加一个额外接收异常的参数,类型为 BlockExceptionblockHandler 函数默认需要和原方法在同一个类中。若希望使用其他类的函数,则可以指定 blockHandlerClass 为对应的类的 Class 对象,注意对应的函数必需为 static 函数,否则无法解析。
  • fallback /fallbackClassfallback 函数名称,可选项,用于在抛出异常的时候提供 fallback 处理逻辑。fallback 函数可以针对所有类型的异常(除了exceptionsToIgnore里面排除掉的异常类型)进行处理。fallback 函数签名和位置要求:

返回值类型必须与原函数返回值类型一致;

方法参数列表需要和原函数一致,或者可以额外多一个 Throwable 类型的参数用于接收对应的异常。

fallback 函数默认需要和原方法在同一个类中。若希望使用其他类的函数,则可以指定 fallbackClass 为对应的类的 Class 对象,

注意对应的函数必需为 static 函数,否则无法解析。

  • defaultFallback(since 1.6.0):默认的 fallback 函数名称,可选项,通常用于通用的 fallback 逻辑(即可以用于很多服务或方法)。默认 fallback 函数可以针对所有类型的异常(除了exceptionsToIgnore里面排除掉的异常类型)进行处理。若同时配置了 fallbackdefaultFallback,则只有 fallback 会生效。defaultFallback 函数签名要求:

返回值类型必须与原函数返回值类型一致;

方法参数列表需要为空,或者可以额外多一个 Throwable 类型的参数用于接收对应的异常。

defaultFallback 函数默认需要和原方法在同一个类中。若希望使用其他类的函数,则可以指定 fallbackClass 为对应的类的 Class 对象,注意对应的函数必需为 static 函数,否则无法解析。

  • exceptionsToIgnore(since 1.6.0):用于指定哪些异常被排除掉,不会计入异常统计中,也不会进入 fallback 逻辑中,而是会原样抛出。

官方文档

Sentinel主要有三个核心Api:

SphU定义资源

Tracer定义统计

ContextUtil定义了上下文

Sentinel服务熔断Ribbon环境预说

sentinel整合ribbon+openFeign+fallback

Ribbon系列

  • 启动nacos和sentinel
  • 提供者9003/9004
  • 消费者84

提供者9003/9004

新建cloudalibaba-provider-payment9003/9004,两个一样的做法

POM

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <parent>
  4. <artifactId>cloud_Parent</artifactId>
  5. <groupId>dhy.xpy</groupId>
  6. <version>520.521.finally</version>
  7. </parent>
  8. <modelVersion>4.0.0</modelVersion>
  9. <artifactId>cloudalibaba-provider-payment9003</artifactId>
  10. <properties>
  11. <maven.compiler.source>16</maven.compiler.source>
  12. <maven.compiler.target>16</maven.compiler.target>
  13. </properties>
  14. <dependencies>
  15. <!--SpringCloud ailibaba nacos -->
  16. <dependency>
  17. <groupId>com.alibaba.cloud</groupId>
  18. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
  19. </dependency>
  20. <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
  21. <groupId>com.dhy.springCloud</groupId>
  22. <artifactId>cloud-api-commons</artifactId>
  23. <version>1.0-SNAPSHOT</version>
  24. </dependency>
  25. <!-- SpringBoot整合Web组件 -->
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-web</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-actuator</artifactId>
  33. </dependency>
  34. <!--日常通用jar包配置-->
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-devtools</artifactId>
  38. <scope>runtime</scope>
  39. <optional>true</optional>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.projectlombok</groupId>
  43. <artifactId>lombok</artifactId>
  44. <optional>true</optional>
  45. </dependency>
  46. <dependency>
  47. <groupId>org.springframework.boot</groupId>
  48. <artifactId>spring-boot-starter-test</artifactId>
  49. <scope>test</scope>
  50. </dependency>
  51. </dependencies>
  52. </project>

YML

  1. server:
  2. port: 9003
  3. spring:
  4. application:
  5. name: nacos-payment-provider
  6. cloud:
  7. nacos:
  8. discovery:
  9. server-addr: localhost:8848 #配置Nacos地址
  10. management:
  11. endpoints:
  12. web:
  13. exposure:
  14. include: '*'

记得修改不同的端口号

主启动

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. public class PaymentMain9003 {
  4. public static void main(String[] args) {
  5. SpringApplication.run(PaymentMain9003.class, args);
  6. }
  7. }

业务类

  1. @RestController
  2. public class PaymentController {
  3. @Value("${server.port}")
  4. private String serverPort;
  5. //模拟数据库
  6. public static HashMap<Long,Payment> hashMap = new HashMap<>();
  7. static
  8. {
  9. hashMap.put(1L,new Payment(1L,"28a8c1e3bc2742d8848569891fb42181"));
  10. hashMap.put(2L,new Payment(2L,"bba8c1e3bc2742d8848569891ac32182"));
  11. hashMap.put(3L,new Payment(3L,"6ua8c1e3bc2742d8848569891xt92183"));
  12. }
  13. @GetMapping(value = "/paymentSQL/{id}")
  14. public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id)
  15. {
  16. Payment payment = hashMap.get(id);
  17. CommonResult<Payment> result = new CommonResult(200,"from mysql,serverPort: "+serverPort,payment);
  18. return result;
  19. }
  20. }

测试地址 - http://localhost:9003/paymentSQL/1

消费者84

新建cloudalibaba-consumer-nacos-order84

POM

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>cloud_Parent</artifactId>
  7. <groupId>dhy.xpy</groupId>
  8. <version>520.521.finally</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>cloudalibaba-consumer-nacos-order84</artifactId>
  12. <properties>
  13. <maven.compiler.source>16</maven.compiler.source>
  14. <maven.compiler.target>16</maven.compiler.target>
  15. </properties>
  16. <dependencies>
  17. <!--SpringCloud openfeign -->
  18. <dependency>
  19. <groupId>org.springframework.cloud</groupId>
  20. <artifactId>spring-cloud-starter-openfeign</artifactId>
  21. </dependency>
  22. <!--SpringCloud ailibaba nacos -->
  23. <dependency>
  24. <groupId>com.alibaba.cloud</groupId>
  25. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
  26. </dependency>
  27. <!--SpringCloud ailibaba sentinel -->
  28. <dependency>
  29. <groupId>com.alibaba.cloud</groupId>
  30. <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
  31. </dependency>
  32. <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
  33. <dependency>
  34. <groupId>com.dhy.springCloud</groupId>
  35. <artifactId>cloud-api-commons</artifactId>
  36. <version>1.0-SNAPSHOT</version>
  37. </dependency>
  38. <!-- SpringBoot整合Web组件 -->
  39. <dependency>
  40. <groupId>org.springframework.boot</groupId>
  41. <artifactId>spring-boot-starter-web</artifactId>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-starter-actuator</artifactId>
  46. </dependency>
  47. <!--日常通用jar包配置-->
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-devtools</artifactId>
  51. <scope>runtime</scope>
  52. <optional>true</optional>
  53. </dependency>
  54. <dependency>
  55. <groupId>org.projectlombok</groupId>
  56. <artifactId>lombok</artifactId>
  57. <optional>true</optional>
  58. </dependency>
  59. <dependency>
  60. <groupId>org.springframework.boot</groupId>
  61. <artifactId>spring-boot-starter-test</artifactId>
  62. <scope>test</scope>
  63. </dependency>
  64. </dependencies>
  65. </project>

YML

  1. server:
  2. port: 84
  3. spring:
  4. application:
  5. name: nacos-order-consumer
  6. cloud:
  7. nacos:
  8. discovery:
  9. server-addr: localhost:8848
  10. sentinel:
  11. transport:
  12. #配置Sentinel dashboard地址
  13. dashboard: localhost:8080
  14. #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
  15. port: 8719
  16. #消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
  17. service-url:
  18. nacos-user-service: http://nacos-payment-provider
  19. # 激活Sentinel对Feign的支持
  20. feign:
  21. sentinel:
  22. enabled: false

主启动

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  4. import org.springframework.cloud.openfeign.EnableFeignClients;
  5. @EnableDiscoveryClient
  6. @SpringBootApplication
  7. @EnableFeignClients
  8. public class OrderNacosMain84 {
  9. public static void main(String[] args) {
  10. SpringApplication.run(OrderNacosMain84.class, args);
  11. }
  12. }

业务类

  1. @Configuration
  2. public class ApplicationContextConfig {
  3. @Bean
  4. @LoadBalanced
  5. public RestTemplate getRestTemplate() {
  6. return new RestTemplate();
  7. }
  8. }
  1. @RestController
  2. @Slf4j
  3. public class CircleBreakerController {
  4. public static final String SERVICE_URL = "http://nacos-payment-provider";
  5. @Resource
  6. private RestTemplate restTemplate;
  7. @RequestMapping("/consumer/fallback/{id}")
  8. @SentinelResource(value = "fallback")//没有配置
  9. public CommonResult<Payment> fallback(@PathVariable Long id)
  10. {
  11. //通过服务名实现负载均衡
  12. CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
  13. if (id == 4) {
  14. throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
  15. }else if (result.getData() == null) {
  16. throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
  17. }
  18. return result;
  19. }
  20. }

注意:

修改后请重启微服务

热部署对java代码级生效及时

对@SentinelResource注解内属性,有时效果不好

目的

fallback管运行异常

blockHandler管配置违规

测试地址 - http://localhost:84/consumer/fallback/1

没有任何配置

只配置fallback

只配置blockHandler

fallback和blockHandler都配置

忽略属性

Sentinel服务熔断无配置

没有任何配置 - 给用户error页面,不友好

  1. @RestController
  2. @Slf4j
  3. public class CircleBreakerController {
  4. public static final String SERVICE_URL = "http://nacos-payment-provider";
  5. @Resource
  6. private RestTemplate restTemplate;
  7. @RequestMapping("/consumer/fallback/{id}")
  8. @SentinelResource(value = "fallback")//没有配置
  9. public CommonResult<Payment> fallback(@PathVariable Long id)
  10. {
  11. CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
  12. if (id == 4) {
  13. throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
  14. }else if (result.getData() == null) {
  15. throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
  16. }
  17. return result;
  18. }
  19. }

Sentinel服务熔断只配置fallback

  1. @RestController
  2. @Slf4j
  3. public class CircleBreakerController {
  4. public static final String SERVICE_URL = "http://nacos-payment-provider";
  5. @Resource
  6. private RestTemplate restTemplate;
  7. @RequestMapping("/consumer/fallback/{id}")
  8. //@SentinelResource(value = "fallback")//没有配置
  9. @SentinelResource(value = "fallback", fallback = "handlerFallback") //fallback只负责业务异常
  10. public CommonResult<Payment> fallback(@PathVariable Long id) {
  11. CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
  12. if (id == 4) {
  13. throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
  14. }else if (result.getData() == null) {
  15. throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
  16. }
  17. return result;
  18. }
  19. //本例是fallback
  20. public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
  21. Payment payment = new Payment(id,"null");
  22. return new CommonResult<>(444,"兜底异常handlerFallback,exception内容 "+e.getMessage(),payment);
  23. }
  24. }

测试地址 - http://localhost:84/consumer/fallback/4

页面返回结果:

  1. {"code":444,"message":"兜底异常nandlerFal1back, exception内容illegalkrgumentEBxceptiorn,非法参数异常……","data":{"id":4,"seria:"null"}}

Sentinel服务熔断只配置blockHandler

  1. @RestController
  2. @Slf4j
  3. public class CircleBreakerController
  4. {
  5. public static final String SERVICE_URL = "http://nacos-payment-provider";
  6. @Resource
  7. private RestTemplate restTemplate;
  8. @RequestMapping("/consumer/fallback/{id}")
  9. //@SentinelResource(value = "fallback") //没有配置
  10. //@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback只负责业务异常
  11. @SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
  12. public CommonResult<Payment> fallback(@PathVariable Long id)
  13. {
  14. CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
  15. if (id == 4) {
  16. throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
  17. }else if (result.getData() == null) {
  18. throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
  19. }
  20. return result;
  21. }
  22. //本例是fallback
  23. /* public CommonResult handlerFallback(@PathVariable Long id,Throwable e) { Payment payment = new Payment(id,"null"); return new CommonResult<>(444,"兜底异常handlerFallback,exception内容 "+e.getMessage(),payment); }*/
  24. //本例是blockHandler
  25. public CommonResult blockHandler(@PathVariable Long id,BlockException blockException) {
  26. Payment payment = new Payment(id,"null");
  27. return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment);
  28. }
  29. }

测试地址 - http://localhost:84/consumer/fallback/4

Sentinel服务熔断fallback和blockHandler都配置

若blockHandler和fallback 都进行了配置,则被限流降级而抛出BlockException时只会进入blockHandler处理逻辑。

  1. @RestController
  2. @Slf4j
  3. public class CircleBreakerController
  4. {
  5. public static final String SERVICE_URL = "http://nacos-payment-provider";
  6. @Resource
  7. private RestTemplate restTemplate;
  8. @RequestMapping("/consumer/fallback/{id}")
  9. //@SentinelResource(value = "fallback") //没有配置
  10. //@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback只负责业务异常
  11. //@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
  12. @SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler")
  13. public CommonResult<Payment> fallback(@PathVariable Long id)
  14. {
  15. CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
  16. if (id == 4) {
  17. throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
  18. }else if (result.getData() == null) {
  19. throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
  20. }
  21. return result;
  22. }
  23. //本例是fallback
  24. public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
  25. Payment payment = new Payment(id,"null");
  26. return new CommonResult<>(444,"兜底异常handlerFallback,exception内容 "+e.getMessage(),payment);
  27. }
  28. //本例是blockHandler
  29. public CommonResult blockHandler(@PathVariable Long id,BlockException blockException) {
  30. Payment payment = new Payment(id,"null");
  31. return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment);
  32. }
  33. }

Sentinel服务熔断exceptionsToIgnore

exceptionsToIgnore,忽略指定异常,即这些异常不用兜底方法处理。

  1. @RestController
  2. @Slf4j
  3. public class CircleBreakerController
  4. ...
  5. @RequestMapping("/consumer/fallback/{id}")
  6. @SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler",
  7. exceptionsToIgnore = {IllegalArgumentException.class})//<-------------
  8. public CommonResult<Payment> fallback(@PathVariable Long id)
  9. {
  10. CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id,CommonResult.class,id);
  11. if (id == 4) {
  12. //exceptionsToIgnore属性有IllegalArgumentException.class,
  13. //所以IllegalArgumentException不会跳入指定的兜底程序。
  14. throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
  15. }else if (result.getData() == null) {
  16. throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
  17. }
  18. return result;
  19. }
  20. ...
  21. }

Sentinel服务熔断OpenFeign

修改84模块

  • 84消费者调用提供者9003
  • Feign组件一般是消费侧

POM

  1. <!--SpringCloud openfeign -->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-openfeign</artifactId>
  5. </dependency>

YML

  1. # 激活Sentinel对Feign的支持
  2. feign:
  3. sentinel:
  4. enabled: true

业务类

带@Feignclient注解的业务接口,fallback = PaymentFallbackService.class

  1. @FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
  2. public interface PaymentService
  3. {
  4. @GetMapping(value = "/paymentSQL/{id}")
  5. public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
  6. }
  1. @Component
  2. public class PaymentFallbackService implements PaymentService {
  3. @Override
  4. public CommonResult<Payment> paymentSQL(Long id)
  5. {
  6. return new CommonResult<>(44444,"服务降级返回,---PaymentFallbackService",new Payment(id,"errorSerial"));
  7. }
  8. }

Controller

  1. @RestController
  2. @Slf4j
  3. public class CircleBreakerController {
  4. ...
  5. //==================OpenFeign
  6. @Resource
  7. private PaymentService paymentService;
  8. @GetMapping(value = "/consumer/paymentSQL/{id}")
  9. public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id)
  10. {
  11. return paymentService.paymentSQL(id);
  12. }
  13. }

主启动

  1. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  2. @EnableDiscoveryClient
  3. @SpringBootApplication
  4. @EnableFeignClients//<------------------------
  5. public class OrderNacosMain84 {
  6. public static void main(String[] args) {
  7. SpringApplication.run(OrderNacosMain84.class, args);
  8. }
  9. }

测试 - http://localhost:84/consumer/paymentSQL/1

测试84调用9003,此时故意关闭9003微服务提供者,84消费侧自动降级,不会被耗死。

熔断框架比较

sentinel持久化规则

一旦我们重启应用,Sentinel规则将消失,生产环境需要将配置规则进行持久化

该怎么做:

将限流配置规则持久化进Nacos保存,只要刷新8401某个rest地址,sentinel控制台的流控规则就能看到,只要Nacos里面的配置不删除,针对8401上Sentinel上的流控规则持续有效

原理:

  • 将规则推送到Nacos或其他远程配置中心•Sentinel客户端链接Nacos,获取规则配置;并监听Nacos配置变化,如发生变化,就更新本地缓存(从而让本地缓存总是和Nacos一致)

步骤

1 加依赖

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

2 添加配置

  1. server:
  2. port: 8401
  3. spring:
  4. application:
  5. name: cloudalibaba-sentinel-service
  6. cloud:
  7. nacos:
  8. discovery:
  9. server-addr: localhost:8848 # 注册进nacos
  10. sentinel:
  11. transport:
  12. dashboard: localhost:8080 #表示要被sentinel监控
  13. port: 8719 #指定应用与Sentinel控制台交互的端口,应用本地会起一个该端口占用的HttpServer
  14. #,默认8719,假如被占用了会自动从8719开始依次+1扫描。直至找到未被占用的端口
  15. datasource: # 添加Nacos数据源配置
  16. ds1:
  17. nacos:
  18. server-addr: localhost:8848 #nacos服务器地址
  19. dataId: ${spring.application.name} #微服务名称是哪一个
  20. groupId: DEFAULT_GROUP #默认分组
  21. data-type: json #数据类型
  22. rule-type: flow
  23. management:
  24. endpoints:
  25. web:
  26. exposure:
  27. include: '*'
  28. feign:
  29. sentinel:
  30. enabled: true # 激活Sentinel对Feign的支持

4、添加Nacos业务规则配置

内容:

  1. [
  2. {
  3. "resource": "/rateLimit/byUrl",
  4. "limitApp": "default",
  5. "grade": 1,
  6. "count": 1,
  7. "strategy": 0,
  8. "controlBehavior": 0,
  9. "clusterMode": false
  10. }
  11. ]

上面就是sentinel配置的那套东西

测试

1、启动8401后刷新sentinel发现业务规则有了

2、快速访问测试接口http://localhost:8401/rateLimit/byUrl

3、停止8401再看sentinel

4、重新启动8401再看sentinel,一看还是没有,稍等一会儿,多次调用http://localhost:8401/rateLimit/byUrl

重新配置出现了,持久化验证通过

相关文章