一、Sentinel

https://github.com/alibaba/Sentinel 中文
Sentinel 是轻量级的流量控制、熔断降级Java库;功能类似于Hystrix
image.png
下载地址
image.png
怎么玩:
入门文档
服务使用中的各种问题:服务雪崩、服务降级、服务熔断、服务限流

二、安装Sentinel控制台

Sentinel分为两个部分:

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

    安装步骤

    下载到本地sentinel-dashboard-1.8.2.jar
    运行命令:
    前提需要Java8,且8080端口不能被占用;java -jar sentinel-dashboard-1.8.2.jar
    image.png
    访问 localhost:8080,账号密码均为sentinel
    image.png

三、初始化演示工程

3.1 启动Nacos8848

3.2 新建Module cloudalibaba-sentinel-service8401

3.2.1 pom

以后基本上nacos 跟sentinel一起配置

  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>jdk8cloud2021</artifactId>
  7. <groupId>com.atguigu.springcloud</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>cloudalibaba-sentinel-service8401</artifactId>
  12. <properties>
  13. <maven.compiler.source>8</maven.compiler.source>
  14. <maven.compiler.target>8</maven.compiler.target>
  15. </properties>
  16. <dependencies>
  17. <!--SpringCloud ailibaba nacos -->
  18. <dependency>
  19. <groupId>com.alibaba.cloud</groupId>
  20. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
  21. </dependency>
  22. <!--SpringCloud ailibaba sentinel-datasource-nacos 后续做持久化用到-->
  23. <dependency>
  24. <groupId>com.alibaba.csp</groupId>
  25. <artifactId>sentinel-datasource-nacos</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. <!--openfeign-->
  33. <dependency>
  34. <groupId>org.springframework.cloud</groupId>
  35. <artifactId>spring-cloud-starter-openfeign</artifactId>
  36. </dependency>
  37. <!-- SpringBoot整合Web组件+actuator -->
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-web</artifactId>
  41. </dependency>
  42. <dependency>
  43. <groupId>org.springframework.boot</groupId>
  44. <artifactId>spring-boot-starter-actuator</artifactId>
  45. </dependency>
  46. <!--日常通用jar包配置-->
  47. <dependency>
  48. <groupId>org.springframework.boot</groupId>
  49. <artifactId>spring-boot-devtools</artifactId>
  50. <scope>runtime</scope>
  51. <optional>true</optional>
  52. </dependency>
  53. <dependency>
  54. <groupId>cn.hutool</groupId>
  55. <artifactId>hutool-all</artifactId>
  56. <version>4.6.3</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.projectlombok</groupId>
  60. <artifactId>lombok</artifactId>
  61. <optional>true</optional>
  62. </dependency>
  63. <dependency>
  64. <groupId>org.springframework.boot</groupId>
  65. <artifactId>spring-boot-starter-test</artifactId>
  66. <scope>test</scope>
  67. </dependency>
  68. </dependencies>
  69. </project>

3.2.2 yaml

spring.cloud.sentinel.transport.port 端口配置会在应用对应的机器上启动一个 Http Server,该 Server 会与 Sentinel 控制台做交互。
比如 Sentinel 控制台添加了1个限流规则,会把规则数据push给这个Http Server接收,Http Server再将规则注册到Sentinel中。
spring.cloud.sentinel.transport.port:指定与Sentinel控制台交互的端口,应用本地会启动一个占用该端口的Http Server

  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. #配置Sentinel dashboard地址
  13. dashboard: localhost:8080
  14. #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
  15. port: 8719
  16. management:
  17. endpoints:
  18. web:
  19. exposure:
  20. include: '*'

3.2.3 主启动类

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

3.2.4 业务类

流量控制controller:FlowLimitController

  1. package com.atguigu.cloudalibaba.controller;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. public class FlowLimitController {
  6. @GetMapping("/testA")
  7. public String testA() {
  8. return "------testA";
  9. }
  10. @GetMapping("/testB")
  11. public String testB() {
  12. return "------testB";
  13. }
  14. }

3.3 测试

启动Sentinel8080 java -jar sentinel-dashboard-1.8.2.jar、启动微服务8401
查看Sentinel控制台,发现什么也没有。
image.png
原因:Sentinel采用懒加载机制
执行一下:http://localhost:8401/testA
image.png
sentinel8080正在监控微服务8401

四、流控规则

流量限制控制规则,分为:流控模式和流控效果
image.png
各选项含义:
image.png

4.1 流控模式

流控模式有三种:直接、关联、链路
image.png

4.1.1 直接(默认)+快速失败(默认)

(1) QPS直接快速失败

QPS:query per second,每秒钟的请求数量,当调用该api的QPS达到阈值时,进行限流。
下面设置表示1秒钟内查询一次就是OK,若QPS>1,就直接-快速失败,报默认错误
image.png
image.png
测试一下,当/testA的访问超过1次/s是,页面报错。被Sentinel限流,还能继续请求只要QPS<=1。
image.png
小结:表示1秒钟内请求次数大于1,就直接快速失败,报默认错误。
image.png
直接调用默认的报错信息在技术上是OK的,但是是否应该有自定义的后续处理?应该有类似Hystrix的fallback的兜底方法。

(2) 线程数直接快速失败

当调用该api的线程数达到阈值的时候,进行限流。
与QPS直接快速失败不同的是,QPS情况下限制的是流量,比如银行的人流量只能是1人/s,也就是说每次只能一个人进入银行办理业务;而线程数就好比银行只有一个窗口开放,一群人都可以进入银行,但是每次只能处理一个人的业务。
image.png
演示效果:
先修改一下8401的业务类
image.png
然后重启8401,测试/testA,最好用两个浏览器访问,效果更明显
image.png

4.1.2 关联

当关联的资源达到阈值时,就限流自己。比如当与A关联的资源B达到阈值后,就限流A自己。
支付接口达到阈值,限流下订单的接口。

1. 配置

设置效果:当关联资源/testB的qps阀值超过1时,就限流/testA的Rest访问地址,当关联资源到阈值后限制配置好的资源名
image.png

2. 测试

单独访问testB成功。
image.png
postman模拟并发密集访问testB
先创建一个集合,名字自己随便取。
image.png
然后将创建的访问/testB的请求保存在创建的集合中
image.png
设定集合运行参数,20个线程,每次间隔0.3s访问一次(QPS>1),执行:
image.png
然后再访问/testA,发现被限流,等postman执行完毕,testA又可以访问了
image.png

4.1.3 链路

需要测试链路的话,springcloud 阿里巴巴版本需要2.1.1.RELEASE以上,在父工程的pom中修改,不要直接在子module的pom中修改,版本有对应关系,不然报错。
image.png
image.png

  • Sentinel从1.6.3版本开始,Sentinel Web Filter 默认收敛所有的URL入口的Context,因此链路限流不生效
  • 1.7.0版本开始,官方在CommomFilter中引入了WEB_CONTEXT_UNIFY这个init parameter,用于控制是否收敛context,将其配置为false即可根据不同的URL进行链路限流
  • Spring Cloud Alibaba 在2.1.1.RELEASE版本后,可以通过配置spring.cloud.sentinel.web-context-unify=false关闭

image.png
https://github.com/alibaba/Sentinel/issues/1313

测试

启动8401,给/testA设置链路+快速失败流控规则:
image.png
这里入口资源就是簇点链路中,资源名称的上一级。
访问http://localhost:8401/linktestA ,多次刷新出现限流
image.png,但是这种情况我个人觉得跟直接快速失败区别不大,只直接是监控/testA资源,而链路是监控/testA的资源入口sentinel_web_servlet_context。

然后我又参看了其他博客,流控模式——链路。增加了FlowLimitService 修改了controller

  1. package com.atguigu.cloudalibaba.service;
  2. import com.alibaba.csp.sentinel.annotation.SentinelResource;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class FlowLimitService {
  6. @SentinelResource("message")
  7. public String message() {
  8. return "success";
  9. }
  10. }
  1. package com.atguigu.cloudalibaba.controller;
  2. import com.atguigu.cloudalibaba.service.FlowLimitService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import java.util.concurrent.TimeUnit;
  7. @RestController
  8. public class FlowLimitController {
  9. @Autowired
  10. FlowLimitService flowLimitService;
  11. @GetMapping("/testA")
  12. public String testA() {
  13. //暂停0.8秒
  14. // try {
  15. // TimeUnit.MILLISECONDS.sleep(800);
  16. // } catch (InterruptedException e) {
  17. // e.printStackTrace();
  18. // }
  19. return "------testA";
  20. }
  21. @GetMapping("/testB")
  22. public String testB() {
  23. return "------testB";
  24. }
  25. // 链路测试
  26. @GetMapping("/linktestA")
  27. public String linktestA() {
  28. return flowLimitService.message();
  29. }
  30. @GetMapping("/linktestB")
  31. public String linktestB() {
  32. return flowLimitService.message();
  33. }
  34. }

分别通过/linktetA 和 /linktestB都是message的入口,然后设置/linktestA入口的流量限制,发现不起作用。。。

4.2 流控效果

快速失败在上面的流控模式演示过了,他是默认的流控效果,直接失败,抛出异常。源码:com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController

4.2.1 warm up 预热

官网 源码:com.alibaba.csp.sentinel.slots.block.flow.controller.WarmUpController
公式:阈值除以coldFactor(默认值为3),经过预热时长后才会达到阈值
image.png

image.png

测试

image.png
狂点请求,可以看通过的QPS逐渐增加,最开始会报错限流,之后就可以抗住10/s的QPS了
应用场景:秒杀系统在开启的瞬间,会有很多流量上来,很有可能把系统打死,预热方式就是把为了保护系统,可慢慢的把流量放进来,慢慢的把阀值增长到设置的阀值。

4.2.2 排队等待

官网 源码:com.alibaba.csp.sentinel.slots.block.flow.controller.RateLimiterController
image.png
匀速排队,让请求以均匀的速度通过,阀值类型必须设成QPS,否则无效。
image.png
/testA的QPS最大为1,超过的话就排队等待,等待的超时时间为20000ms。

修改一下业务代码,把线程名打印出来以验证是否排队。
image.png

测试

postman:
image.png
image.png
可以看到刚好满足1s一个请求,说明请求的执行进行了排队。

五、降级规则(熔断规则)

官网
老版本的Sentinel的断路器是没有半开状态的,半开的状态系统自动去检测是否请求有异常,没有异常就关闭断路器恢复使用,有异常则继续打开断路器不可用。具体可以参考Hystrix。(在Hystrix中 快照时间窗口是值 阈值检测时间 ,而休眠时间窗口是指 断路器从开启到半开状态间隔的时间)
新版本的Sentinel加入了半开状态

5.1 降级策略

Sentinel 熔断降级会在调用链路中某个资源出现不稳定状态时(例如调用超时或异常比例升高),对这个资源的调用进行限制,让请求快速失败,避免影响到其它的资源而导致级联错误。
当资源被降级后,在接下来的降级时间窗口之内,对该资源的调用都自动熔断(默认行为是抛出 DegradeException)。
image.png

5.1.1 慢调用比例,RT(平均响应时间,秒级)

老版本:
image.png
新版本:

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

image.png

实战测试

业务类中加一个rest 接口,以用于测试:

  1. @GetMapping("/testD")
  2. public String testD() {
  3. //暂停1秒
  4. try {
  5. TimeUnit.MILLISECONDS.sleep(1000);
  6. } catch (InterruptedException e) {
  7. e.printStackTrace();
  8. }
  9. log.info("testD 测试慢调用比例 RT");
  10. return "------tedtD";
  11. }

image.png 访问没有问题

编辑熔断规则:
在1000ms的统计时间内,总请求数(超过5次)中有80%的请求最大RT超过了200ms,那么触发熔断机制,熔断2s。
image.png

jmeter压测:
image.png
永远一秒钟打进来10个线程(大于5个了)调用testD,我们希望200毫秒处理完本次任务,如果超过200毫秒还没处理完,在未来s秒钟的时间内,断路器打开(保险丝跳闸)微服务不可用,保险丝跳闸断电了。
testD被熔断了
image.png
从实时监控也可以看到,在09的时候开始熔断。
image.png
后续我停止jmeter,没有这么大的访问量了,断路器半开到关闭(保险丝恢复),微服务恢复OK。

5.1.2 异常比例

老版本:
image.png
新版本:

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

image.png

实战测试

修改业务类:
image.png

编辑熔断规则:
image.png
1000ms统计时长内,大于5次的请求中超过80%的请求出现异常,则熔断2s。

jmeter压测:
单独访问一次,必然来一次报错一次(int age = 10/0),调一次错一次;开启jmeter后,直接高并发发送请求,多次调用达到我们的配置条件了。断路器开启(保险丝跳闸),微服务不可用了,不再报错error而是服务降级了。
image.pngtestD被熔断。
停掉jemeter后过2s。报/zero错误,因为业务类中有个10/0。

5.1.3 异常数

老版本:
image.png
时间窗口一定要大于等于60秒。
新版本

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

image.png

实战测试

修改业务类:
image.png
编辑熔断规则:
image.png

手动测试:
image.png
这里我测试有bug,虽然熔断了但是熔断时长不是我配置的5s,大约是一分钟,统计时长也不是1s,好像也是一分钟,同时没达到最小请求数,只达到3次异常就直接熔断了。虽然我用的新版本,但是逻辑好像跟老版本的一样?

六、热点key限流

6.1 基本介绍

官网
何为热点:热点即经常访问的数据,很多时候我们希望统计或者限制某个热点数据中访问频次最高的TopN数据,并对其访问进行限流或者其它操作。比如:

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

热点参数限制会统计传入参数中的热点参数,并根据配置的限流阈值与模式,对包含热点参数的资源调用进行限制。热点参数限流可以看作是一种特殊的流量控制,仅对包含热点参数的资源调用生效。
image.png
Sentinel利用LRU策略统计最近最常访问的热电参数,结合令牌桶算法来进行参数级别的流控。热点参数限流支持集群模式。

6.2 基本使用

兜底防范分为系统默认和客户自定义;两种,根据之前的case,都是使用sentinel系统默认的提示:Blocked by Sentinel (flow limiting)。那我们能不能自定义兜底方法呢?类似hystrix,某个方法出问题了,就找对应的兜底降级方法?
类似于@HystrixCommand, 引入@SentinelResource注解。
热点规则共有资源名、限流模式(只支持QPS模式)、参数索引、单机阈值、统计窗口时长、是否集群6种参数,还有一些高级选项,用到时会详细介绍。这里会用到注解中的value作为资源名,兜底方法会在后面详细介绍@SentinelResource注解详解
image.png
注意:

资源名:唯一路径,默认为请求路径。此处必须是 @SentinelResource 注解的 value 属性值,配置@GetMapping 的请求路径无效)

6.2.1 测试方法

还是在8401的controller中,加入热点测试方法。

  1. @GetMapping("/testHotKey")
  2. @SentinelResource(value = "testHotKey", blockHandler = "del_testHotKey") //这里的名称可以随便写,但是一般跟rest地址一样
  3. public String testHotkey(@RequestParam(value = "p1", required = false) String p1,
  4. @RequestParam(value = "p1", required = false) String p2) {
  5. return "------testHotkey";
  6. }
  7. //这里是我们自定义的兜底方法,BlockException不要打成了BlockedException
  8. public String del_testHotKey(String p1, String p2, BlockException e) {
  9. return "这次不用默认的兜底提示Blocked by Sentinel(flow limiting),自定义提示:del_testHotKeyo(╥﹏╥)o...";
  10. }

注解@SentinelResource(value = “testHotKey”, blockHandler = “del_testHotKey”)
分析:

  • 其中 value = “testHotKey” 是一个标识(Sentinel资源名),与rest的/testHotKey对应,这里value的值可以任意写,但是我们约定与rest地址一致,唯一区别是没有/
  • blockHandler = “del_testHotKey” 则表示如果违背了Sentinel中配置的流控规则,就会调用我们自己的兜底方法del_testHotKey

    6.2.2 配置热点key限流规则

    绑定testHotKey资源,把testHotKey对应的第一个参数作为热点key进行监控。设定热点限流规则:当该资源的访问QPS超过1次/s的时候,产生限流并执行自定义的del_testHotKey兜底方法。
    简而言之:方法testHotKey里面第一个参数只要QPS超过每秒1次,马上降级处理。
    image.png

6.2.3 测试

  1. 访问http://localhost:8401/testHotKey?p1=a&p2=b

1次/s正常显示,迅速点击两次,触发热点限流,执行自定义兜底方法:
image.png

  1. 仅传入参数p2没有任何影响: http://localhost:8401/testHotKey?p2=b

image.png

  1. 现在开两个访问,一个通过jmeter压测http://localhost:8401/testHotKey?p1=a&p2=b,另外再单独使用浏览器访问http://localhost:8401/testHotKey?p2=b,发现只带参数p2访问没有任何影响。

image.png

  1. 不配置blockeHandler(兜底方法)

image.png
触发热点限流降级会出现error page,对用户不友好。
image.png

6.3 参数例外项

上述案例演示了第一个参数p1,当QPS超过1秒1次点击后马上被限流
特例情况:我们期望p1参数当它是某个特殊值时,它的限流值和平时不一样,比如当p1的值等于5时,它的阈值可以达到200。

image.png

测试
狂点http://localhost:8401/testHotKey?p1=5&p2=b 没有限流
image.png

6.4 其他

手动添加一个异常:
image.png
测试直接错误页面。
image.png
要注意: Sentinel它只管你有没有触发它的限流规则,也可以说只管这个web交互页面(控制台)里面的东西。 配置类的东西Sentinel可以管,java异常的错误我不管。
@SentinelResource
处理的是Sentinel控制台配置的违规情况,有blockHandler方法配置的兜底处理;
RuntimeException
int age = 10/0,这个是java运行时报出的运行时异常RunTimeException,@SentinelResource不管
总结:
@SentinelResource主管配置出错,运行出错该走异常走异常

七、系统规则(系统自适应限流)

官网
Sentinel 系统自适应限流从整体维度对应用入口流量进行控制,结合应用的 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 达到阈值即触发系统保护。

    案例——配置全局QPS

    image.png
    不管是/testA还是/testB 只要QPS > 1 整个系统就不能用。
    这个粒度太粗,就相当于一个窗口人很多,整个银行就不接待人了,不太建议使用。

    八、@SentinelResource 注解详解

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

    启动nacos+sentinel

    8.1.1 修改8401

    (1) pom

    引入我们自定义的公共api jar包
    1. <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
    2. <groupId>com.atguigu.springcloud</groupId>
    3. <artifactId>cloud-api-commons</artifactId>
    4. <version>${project.version}</version>
    5. </dependency>

    (2) 业务类

    ```java package com.atguigu.cloudalibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.atguigu.springcloud.entities.CommonResult; import com.atguigu.springcloud.entities.Payment; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;

@RestController public class RateLimitController { @GetMapping(“/byResource”) @SentinelResource(value = “byResource”, blockHandler = “handleException”) public CommonResult byResource() { return new CommonResult(200, “按资源名称限流测试OK”, new Payment(2020L, “serial001”)); }

  1. public CommonResult handleException(BlockException exception) {
  2. return new CommonResult(444, exception.getClass().getCanonicalName() + "\t 服务不可用");
  3. }

}

  1. <a name="LdBS8"></a>
  2. ### 8.1.2 配置流控规则——按资源名称添加流控规则
  3. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/22423156/1636285393933-ddc0a9ee-ed0e-440f-bc83-48cd579dcc76.png#clientId=u7b3b1ddf-c335-4&from=paste&height=301&id=u1fb1a787&margin=%5Bobject%20Object%5D&name=image.png&originHeight=301&originWidth=627&originalType=binary&ratio=1&size=13499&status=done&style=none&taskId=u9922d51c-0934-48bf-aa04-146f092f823&width=627)
  4. <a name="SX658"></a>
  5. ### 8.1.3 测试
  6. 自测:<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/22423156/1636285275609-5ad7070a-105e-4aec-8237-202601cd4b82.png#clientId=u7b3b1ddf-c335-4&from=paste&height=203&id=ua4ba5dbd&margin=%5Bobject%20Object%5D&name=image.png&originHeight=203&originWidth=445&originalType=binary&ratio=1&size=11285&status=done&style=none&taskId=u03059825-40cf-4756-b42f-71817682170&width=445)<br />触发流控规则:<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/22423156/1636285458697-f546d3c3-34da-491e-a379-b0ccfcf2cc9e.png#clientId=u7b3b1ddf-c335-4&from=paste&height=157&id=udb9e9ccb&margin=%5Bobject%20Object%5D&name=image.png&originHeight=157&originWidth=525&originalType=binary&ratio=1&size=11413&status=done&style=none&taskId=u0cdfcfbc-c93e-4091-838b-cdca4a847ce&width=525)
  7. <a name="K0Qon"></a>
  8. ### 8.1.4 问题
  9. 如果我们重启8401会发现之前配置的一些规则都没有了。难道每次重启服务器都要重新配置一遍规则吗?规则如何进行持久化?
  10. <a name="Leb1u"></a>
  11. ## 8.2 按照Url地址限流+后续处理
  12. 通过访问的URL来限流,会返回Sentinel自带默认的限流处理信息
  13. <a name="jE7ne"></a>
  14. ### 8.2.1 修改controller
  15. ```java
  16. @GetMapping("/rateLimit/byUrl")
  17. @SentinelResource(value = "byUrl")
  18. public CommonResult byUrl()
  19. {
  20. return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002"));
  21. }

8.2.2 设置流控规则及测试

先自测,没有问题:
image.png

按rest URI设置流控规则
image.png

触发流控:
image.png
这个没有自定义的兜底的方法,返回Sentinel自带的限流处理结果。

8.3 总结以及面临的问题

不管是@GetMapping(rest url)还是 @SentinelResource,只要是唯一的,就可以作为流控规则的资源名称。如果没有自定义自己的兜底方法,那么就使用系统自带的。

问题:

  • 依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观。如果都用系统默认的,就没有体现我们自己的业务要求。
  • 如果每个业务方法/API接口都添加一个兜底的,那代码膨胀加剧。
  • 全局统一的处理方法没有体现。

    8.4 客户自定义限流处理逻辑

    为了解决代码耦合与膨胀的问题

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

    在CustomerBlockHandler类中统一的处理限流提示、服务降级的说明等等。。 ```java package com.atguigu.cloudalibaba.myhandler;

import com.alibaba.csp.sentinel.slots.block.BlockException; import com.atguigu.springcloud.entities.CommonResult; import com.atguigu.springcloud.entities.Payment;

public class CustomerBlockHandler { public static CommonResult handlerException(BlockException e) { return new CommonResult(4444, “按客户自定义, global handlerException——1”); }

  1. public static CommonResult handlerException2(BlockException e) {
  2. return new CommonResult(4444, "按客户自定义, global handlerException----2");
  3. }

}

  1. <a name="tEra4"></a>
  2. ### 8.4.2 修改RateLimitController,使用自定义处理逻辑类
  3. ```java
  4. package com.atguigu.cloudalibaba.controller;
  5. import com.alibaba.csp.sentinel.annotation.SentinelResource;
  6. import com.alibaba.csp.sentinel.slots.block.BlockException;
  7. import com.atguigu.cloudalibaba.myhandler.CustomerBlockHandler;
  8. import com.atguigu.springcloud.entities.CommonResult;
  9. import com.atguigu.springcloud.entities.Payment;
  10. import org.springframework.web.bind.annotation.GetMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. @RestController
  13. public class RateLimitController {
  14. @GetMapping("/byResource")
  15. @SentinelResource(value = "byResource", blockHandler = "handleException")
  16. public CommonResult byResource() {
  17. return new CommonResult(200, "按资源名称限流测试OK", new Payment(2020L, "serial001"));
  18. }
  19. public CommonResult handleException(BlockException exception) {
  20. return new CommonResult(444, exception.getClass().getCanonicalName() + "\t 服务不可用");
  21. }
  22. @GetMapping("/rateLimit/byUrl")
  23. @SentinelResource(value = "byUrl")
  24. public CommonResult byUrl() {
  25. return new CommonResult(200, "按url限流测试OK", new Payment(2020L, "serial002"));
  26. }
  27. //CustomerBlockHandler自定义类,来处理服务降级、限流提示.....
  28. /**
  29. * 自定义通用的限流处理逻辑,
  30. * blockHandlerClass = CustomerBlockHandler.class
  31. * blockHandler = handleException2
  32. * 上述配置:找CustomerBlockHandler类里的handleException2方法进行兜底处理
  33. */
  34. //自定义通用的限流处理逻辑
  35. @GetMapping("/rateLimit/customerBlockHandler")
  36. @SentinelResource(value = "customerBlockHandler",
  37. blockHandlerClass = CustomerBlockHandler.class,
  38. blockHandler = "handlerException2")
  39. public CommonResult customerBlockHandler() {
  40. return new CommonResult(200, "按客户自定义", new Payment(2020L, "serial003"));
  41. }
  42. }

8.4.3 测试

启动8401,先测试一次http://localhost:8401/rateLimit/customerBlockHandler
image.png
设置流控规则:
image.png
触发流控,看是否是我们自定义提示:
image.png
自定义提示出来了!

8.4.4 结构说明

image.png
这样就实现了兜底方法与业务方法的解耦。

8.5 更多属性说明

注解支持文档
image.png
image.png

九、服务熔断

主要内容:

  • sentinel分别整合ribbon+openFeign以及设置fallback
  • 熔断框架比较

    9.1 Ribbon系列

    nacos中整合了Ribbon,所以直接使用nacos就行。启动nacos和Sentinel。

    9.1.1 服务提供者9003/9004

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

    (1) pom

    2020版和springcloud和nacos记得引入spring-cloud-starter-loadbalancer依赖

    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>jdk8cloud2021</artifactId>
    7. <groupId>com.atguigu.springcloud</groupId>
    8. <version>1.0-SNAPSHOT</version>
    9. </parent>
    10. <modelVersion>4.0.0</modelVersion>
    11. <artifactId>cloudalibaba-provider-payment9003</artifactId>
    12. <properties>
    13. <maven.compiler.source>8</maven.compiler.source>
    14. <maven.compiler.target>8</maven.compiler.target>
    15. </properties>
    16. <dependencies>
    17. <!--SpringCloud ailibaba nacos -->
    18. <dependency>
    19. <groupId>com.alibaba.cloud</groupId>
    20. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    21. </dependency>
    22. <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
    23. <groupId>com.atguigu.springcloud</groupId>
    24. <artifactId>cloud-api-commons</artifactId>
    25. <version>${project.version}</version>
    26. </dependency>
    27. <!-- SpringBoot整合Web组件 -->
    28. <dependency>
    29. <groupId>org.springframework.boot</groupId>
    30. <artifactId>spring-boot-starter-web</artifactId>
    31. </dependency>
    32. <dependency>
    33. <groupId>org.springframework.boot</groupId>
    34. <artifactId>spring-boot-starter-actuator</artifactId>
    35. </dependency>
    36. <!--日常通用jar包配置-->
    37. <dependency>
    38. <groupId>org.springframework.boot</groupId>
    39. <artifactId>spring-boot-devtools</artifactId>
    40. <scope>runtime</scope>
    41. <optional>true</optional>
    42. </dependency>
    43. <dependency>
    44. <groupId>org.projectlombok</groupId>
    45. <artifactId>lombok</artifactId>
    46. <optional>true</optional>
    47. </dependency>
    48. <dependency>
    49. <groupId>org.springframework.boot</groupId>
    50. <artifactId>spring-boot-starter-test</artifactId>
    51. <scope>test</scope>
    52. </dependency>
    53. </dependencies>
    54. </project>

    (2) yml

    9004 别忘了改端口号 ```yaml server: port: 9003

spring: application: name: nacos-payment-provider cloud: nacos: discovery: server-addr: localhost:8848 #配置Nacos地址

management: endpoints: web: exposure: include: ‘*’

  1. <a name="WQCxT"></a>
  2. #### (3) 主启动类
  3. ```java
  4. package com.atguigu.cloudalibaba;
  5. import org.springframework.boot.SpringApplication;
  6. import org.springframework.boot.autoconfigure.SpringBootApplication;
  7. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  8. @EnableDiscoveryClient
  9. @SpringBootApplication
  10. public class PaymentMain9003 {
  11. public static void main(String[] args) {
  12. SpringApplication.run(PaymentMain9003.class, args);
  13. }
  14. }

(4) 业务类

这里图方便,就没有连接数据库。

  1. package com.atguigu.cloudalibaba.controller;
  2. import com.atguigu.springcloud.entities.CommonResult;
  3. import com.atguigu.springcloud.entities.Payment;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import java.util.HashMap;
  9. @RestController
  10. public class PaymentController {
  11. @Value("${server.port}")
  12. private String serverPort;
  13. public static HashMap<Long, Payment> hashMap = new HashMap<>();
  14. static {
  15. hashMap.put(1L, new Payment(1L, "28a8c1e3bc2742d8848569891fb42181"));
  16. hashMap.put(2L, new Payment(2L, "bba8c1e3bc2742d8848569891ac32182"));
  17. hashMap.put(3L, new Payment(3L, "6ua8c1e3bc2742d8848569891xt92183"));
  18. }
  19. @GetMapping(value = "/paymentSQL/{id}")
  20. public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
  21. Payment payment = hashMap.get(id);
  22. CommonResult<Payment> result = new CommonResult(200, "from mysql,serverPort: " + serverPort, payment);
  23. return result;
  24. }
  25. }

(5) 测试

http://localhost:9003/paymentSQL/1
image.png
http://localhost:9004/paymentSQL/1
image.png

9.1.2 服务消费者84

新建cloudalibaba-consumer-nacos-order84

(1) 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>jdk8cloud2021</artifactId>
  7. <groupId>com.atguigu.springcloud</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>cloudalibaba-consumer-nacos-order84</artifactId>
  12. <properties>
  13. <maven.compiler.source>8</maven.compiler.source>
  14. <maven.compiler.target>8</maven.compiler.target>
  15. </properties>
  16. <dependencies>
  17. <!--SpringCloud ailibaba nacos -->
  18. <dependency>
  19. <groupId>com.alibaba.cloud</groupId>
  20. <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
  21. </dependency>
  22. <!--SpringCloud ailibaba sentinel -->
  23. <dependency>
  24. <groupId>com.alibaba.cloud</groupId>
  25. <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
  26. </dependency>
  27. <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
  28. <dependency>
  29. <groupId>com.atguigu.springcloud</groupId>
  30. <artifactId>cloud-api-commons</artifactId>
  31. <version>${project.version}</version>
  32. </dependency>
  33. <!-- SpringBoot整合Web组件 -->
  34. <dependency>
  35. <groupId>org.springframework.boot</groupId>
  36. <artifactId>spring-boot-starter-web</artifactId>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-actuator</artifactId>
  41. </dependency>
  42. <!--日常通用jar包配置-->
  43. <dependency>
  44. <groupId>org.springframework.boot</groupId>
  45. <artifactId>spring-boot-devtools</artifactId>
  46. <scope>runtime</scope>
  47. <optional>true</optional>
  48. </dependency>
  49. <dependency>
  50. <groupId>org.projectlombok</groupId>
  51. <artifactId>lombok</artifactId>
  52. <optional>true</optional>
  53. </dependency>
  54. <dependency>
  55. <groupId>org.springframework.boot</groupId>
  56. <artifactId>spring-boot-starter-test</artifactId>
  57. <scope>test</scope>
  58. </dependency>
  59. </dependencies>
  60. </project>

(2) 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. #方便controller的@value获取
  18. service-url:
  19. nacos-user-service: http://nacos-payment-provider

(3) 主启动类

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

(4) 业务类

因为用的Ribbon,需要使用其提供的RestTemplate

  1. package com.atguigu.cloudalibaba.config;
  2. import org.springframework.cloud.client.loadbalancer.LoadBalanced;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.web.client.RestTemplate;
  6. @Configuration
  7. public class ApplicationContextConfig {
  8. @Bean
  9. @LoadBalanced //不要忘了
  10. public RestTemplate getRestemplate() {
  11. return new RestTemplate();
  12. }
  13. }
  1. package com.atguigu.cloudalibaba.controller;
  2. import com.alibaba.csp.sentinel.annotation.SentinelResource;
  3. import com.atguigu.springcloud.entities.CommonResult;
  4. import com.atguigu.springcloud.entities.Payment;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.web.bind.annotation.PathVariable;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10. import org.springframework.web.client.RestTemplate;
  11. @RestController
  12. public class CircleBreakerController {
  13. @Value("${service-url.nacos-user-service}")
  14. private static String SERVICE_URL;
  15. //public static final String SERVICE_URL = "http://nacos-payment-provider";
  16. @Autowired
  17. RestTemplate restTemplate;
  18. @RequestMapping("/consumer/fallback/{id}")
  19. @SentinelResource(value = "fallback") //没有配置
  20. public CommonResult<Payment> fallback(@PathVariable Long id) {
  21. CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
  22. if (id == 4) {
  23. throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
  24. } else if (result.getData() == null) {
  25. throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
  26. }
  27. return result;
  28. }
  29. }

(5) 测试

负载均衡实现。
image.png
image.png

9.1.3 fallback 和 blockHandler

加深@SentinelResource(value = “xxx”, fallback = “fffff”, blockHandler = “bbbbbb”)注解理解:
fallback管运行异常,blockHandler管配置违规。
fallback对应服务降级,就是服务出错了应该怎么办(需要有个兜底方法);
blockHandler对应服务熔断,就是我现在服务不可用,我应该怎么办,怎么给客户一个户提示(同样需要一个兜底方法)

9.1.4 差异化配置

这里改的业务类代码均是消费者84端的业务类代码,不要搞错了。
降级是服务业务代码出现错误的兜底,熔断是服务不可用。降级是兜底方法,熔断是对服务保护时间窗口期服务不可用。

(1) 没有任何配置

前面我们的84消费端,@SentinelResource里面只配置了value,fallback和blockHandler都没有配置,该情况下我们测试一下http://localhost:84/consumer/fallback/4
image.png
出现了错误页面,error page对客户不友好,所以我们需要有兜底方法。

(2) 只配置fallback

fallback对应服务降级,就是服务可以正常访问,但是业务逻辑出现错误,需要降级兜底。

  1. @RequestMapping("/consumer/fallback/{id}")
  2. //@SentinelResource(value = "fallback") //没有配置
  3. @SentinelResource(value = "fallback", fallback = "handlerFallback") //fallback负责业务异常
  4. public CommonResult<Payment> fallback(@PathVariable Long id) {
  5. CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
  6. if (id == 4) {
  7. throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
  8. } else if (result.getData() == null) {
  9. throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
  10. }
  11. return result;
  12. }
  13. public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
  14. Payment payment = new Payment(id,"null");
  15. return new CommonResult<>(444,"兜底异常handlerFallback,exception内容 "+e.getMessage(),payment);
  16. }

image.png
访问http://localhost:84/consumer/fallback/4,可以看到业务异常
image.png
image.png

(3) 只配置blockHandler

blockHandler对应服务熔断,当前sentinel配置已经违规(RT数过多、异常过多),服务熔断后不可用,需要给客户提示,进行一个熔断的兜底。

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

image.png
配置sentinel
image.png
访问:http://localhost:84/consumer/fallback/5
image.png
image.png
这里还是跟之前一样的bug,很迷。

(4) fallback和blockHandler都配置

同时有降级跟熔断的兜底方法,当降级达到sentinel配置规则后,触发熔断。

  1. @RequestMapping("/consumer/fallback/{id}")
  2. @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler")
  3. public CommonResult<Payment> fallback(@PathVariable Long id) {
  4. CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
  5. if (id == 4) {
  6. throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
  7. } else if (result.getData() == null) {
  8. throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
  9. }
  10. return result;
  11. }
  12. //本例是fallback
  13. public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
  14. Payment payment = new Payment(id,"null");
  15. return new CommonResult<>(444,"兜底异常handlerFallback,exception内容 "+e.getMessage(),payment);
  16. }
  17. //本例是blockHandler
  18. public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
  19. Payment payment = new Payment(id,"null");
  20. return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "
  21. + blockException.getMessage(),payment);
  22. }

image.png
配置sentinel
删除之前的熔断规则,配置流控:
image.png
限流效果:
image.png

没有触发限流时,我们触发业务异常http://localhost:84/consumer/fallback/4,会被降级方法fallback兜底:
image.png
触发限流时,我们仍然访问可以触发业务异常的连接,此时服务已经被限流(可以理解为服务不可用即熔断),此时触发的是限流(熔断blockHandler):
image.png
也就是说,同时配置fallback:处理业务异常(微服务自身异常,服务降级)和blockHandler:处理触发sentinel配置(微服务不可用,服务熔断)时。在没有违反sentinel规则时,出现业务异常(降级)走fallback方法;违反了sentinel规则时,直接微服务不可用(熔断),走blockHandler指定的自定义方法。

(5) 异常忽略属性

可以选择性的配置当某些异常发生时,不触发fallback的兜底方法。

  1. @RequestMapping("/consumer/fallback/{id}")
  2. @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler",
  3. exceptionsToIgnore = {IllegalArgumentException.class})
  4. public CommonResult<Payment> fallback(@PathVariable Long id) {
  5. CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/" + id, CommonResult.class, id);
  6. if (id == 4) {
  7. throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
  8. } else if (result.getData() == null) {
  9. throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
  10. }
  11. return result;
  12. }
  13. //本例是fallback
  14. public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
  15. Payment payment = new Payment(id,"null");
  16. return new CommonResult<>(444,"兜底异常handlerFallback,exception内容 "+e.getMessage(),payment);
  17. }
  18. //本例是blockHandler
  19. public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
  20. Payment payment = new Payment(id,"null");
  21. return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "
  22. + blockException.getMessage(),payment);
  23. }

image.png
测试一下,访问:http://localhost:84/consumer/fallback/4
image.png
直接报错误页面,没有了降级兜底方法。
其他异常不受影响:
image.png

当然,触发流控之后,仍然通过blockHandler指定的方法进行熔断兜底。

9.2 Feign系列

9.2.1 修改84模块

修改84模块,Feign组件一般是在消费侧。

(1) pom

pom 加入feign的依赖

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

(2) yml

激活Sentinel对Feign的支持

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

(3) 业务类

后续84的controller不找restTemplate(Ribbon),不是restTemplate去调用payment微服务中的接口。而是通过调用PaymentFeignService,service再去调用payment微服务中的端口。

Feign需要定义一个业务逻辑(service)接口+ @FeignClient注解以调用服务提供者。
新建PaymentFeignService interface:

  1. package com.atguigu.cloudalibaba.service;
  2. import com.atguigu.springcloud.entities.CommonResult;
  3. import com.atguigu.springcloud.entities.Payment;
  4. import org.springframework.cloud.openfeign.FeignClient;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. // 指明调用失败的兜底方法在PaymentFallbackService
  8. // 使用 fallback 方式是无法获取异常信息的,
  9. // 如果想要获取异常信息,可以使用 fallbackFactory参数
  10. @FeignClient(value = "nacos-payment-provider", fallback = PaymentFallbackService.class)
  11. public interface PaymentFeignService {
  12. //去nacos-payment-provider服务中找相应的接口
  13. // 方法签名一定要和nacos-payment-provider中controller的一致
  14. // 对应9003、9004中的方法
  15. @GetMapping(value = "/paymentSQL/{id}")
  16. public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
  17. }

调用失败的兜底方法:

  1. package com.atguigu.cloudalibaba.service;
  2. import com.atguigu.springcloud.entities.CommonResult;
  3. import com.atguigu.springcloud.entities.Payment;
  4. import org.springframework.stereotype.Component;
  5. @Component //不要忘记了
  6. public class PaymentFallbackService implements PaymentFeignService {
  7. //如果nacos-payment-consumer服务中的相应接口出事了,我来兜底
  8. @Override
  9. public CommonResult<Payment> paymentSQL(Long id) {
  10. return new CommonResult<>(444,"服务降级返回,没有该流水信息-------PaymentFallbackService",new Payment(id, "errorSerial......"));
  11. }
  12. }

84端口controller加入openFeign的接口:

  1. //==================OpenFeign
  2. @Resource
  3. private PaymentFeignService paymentFeignService;
  4. @GetMapping(value = "/consumer/paymentSQL/{id}")
  5. public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
  6. if (id == 4) {
  7. throw new RuntimeException("没有该id");
  8. }
  9. return paymentFeignService.paymentSQL(id);
  10. }

(4) 主启动类

加上@EnableFeignClient注解开启OpenFeign

(5) 测试

启动9003、9004、84
访问:http://localhost:84/consumer/paymentSQL/1
9003、9004负载均衡
image.png
image.png
关闭9003、9004微服务提供者,看到84消费者自动执行降级兜底方法。
image.png
如果yaml没有配置Sentinel对Feign的支持,就不会执行降级方法,而是直接报错误页面。
image.png

9.3 熔断框架比较

image.png

十、持久化规则

前面我们微服务新增的限流规则后,微服务关闭后就会丢失,当时配置都限流规则都是临时的。 将限流配置规则持久化进Nacos保存,只要刷新8401某个rest地址,sentinel控制台的流控规则 就能看到。只要nacos里面的配置不删除,针对8401上的sentinel上的流控规则就持续存在。 (也可以持久化到文件,redis,数据库等)

案例——修改8401已完成持久化设置

(1) pom

导入持久化所需依赖

  1. <!--SpringCloud ailibaba sentinel-datasource-nacos 持久化-->
  2. <dependency>
  3. <groupId>com.alibaba.csp</groupId>
  4. <artifactId>sentinel-datasource-nacos</artifactId>
  5. </dependency>

(2) yaml

添加nacos数据源配置

  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. #配置Sentinel dashboard地址
  13. dashboard: localhost:8080
  14. #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
  15. port: 8719
  16. # 关闭默认收敛所有URL的入口context,不然链路限流不生效
  17. # Spring Cloud Alibaba 需要2.1.1.RELEASE以上版本
  18. web-context-unify: false
  19. # filter:
  20. # enabled: false # 关闭自动收敛
  21. #持久化配置
  22. datasource:
  23. ds1:
  24. nacos:
  25. server-addr: localhost:8848
  26. dataId: cloudalibaba-sentinel-service
  27. groupId: DEFAULT_GROUP
  28. data-type: json
  29. rule-type: flow
  30. management:
  31. endpoints:
  32. web:
  33. exposure:
  34. include: '*'

(3) 添加nacos业务规则配置

我们将sentinel的流控配置保存在nacos中,因为nacos的配置持久化在了数据库中。
image.png

  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. ]

resource:资源名称;
limitApp:来源应用;
grade:阈值类型,0表示线程数,1表示QPS;
count:单机阈值;
strategy:流控模式,0表示直接,1表示关联,2表示链路;
controlBehavior:流控效果,0表示快速失败,1表示Warm Up,2表示排队等待;
clusterMode:是否集群。

注意:这里如果要配nacos的命名空间(public、dev、test)的话,应该是配namespace的id,不是名称

(4) 测试

启动8401,访问8401任意接口,刷新Sentinel。可以看到Sentinel中加载了通过nacos持久化的规则配置文件。
image.png

关掉8401后发现流控规则没有了。
image.png

再次启动8401查看sentinel,访问几次8401后流控规则又出现了。
查看数据库,发现规则持久化到数据库中了。
image.png