④ Sentinel 【熔断与限流】
4.1 Sentinel简介
分布式系统的流量防卫兵
官网:https://github.com/alibaba/Sentinel
随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
Sentinel 具有以下特征:
- 丰富的应用场景:Sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景,例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、集群流量控制、实时熔断下游不可用应用等。
- 完备的实时监控:Sentinel 同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机器秒级数据,甚至 500 台以下规模的集群的汇总运行情况。
- 广泛的开源生态:Sentinel 提供开箱即用的与其它开源框架/库的整合模块,例如与 Spring Cloud、Dubbo、gRPC 的整合。您只需要引入相应的依赖并进行简单的配置即可快速地接入 Sentinel。
- 完善的 SPI 扩展点:Sentinel 提供简单易用、完善的 SPI 扩展接口。您可以通过实现扩展接口来快速地定制逻辑。例如定制规则管理、适配动态数据源等。
Sentinel 的主要特性:
Sentinel 分为两个部分:
- 核心库(Java 客户端)不依赖任何框架/库,能够运行于所有 Java 运行时环境,同时对 Dubbo / Spring Cloud 等框架也有较好的支持。
- 控制台(Dashboard)基于 Spring Boot 开发,打包后可以直接运行,不需要额外的 Tomcat 等应用容器。
Sentinel的下载与安装
- 进入文件目录直接运行jar包就行(运行命令为: java -jar xxxx.jar)
- 访问sentinel管理界面 (localhost:8080/)
- 账号密码全为sentinel
- 安装完成
4.2 初始化监控
- 新建模块springcloudalibaba-sentinel-service8401,导入依赖
<!--pom.xml依赖-->
<dependencies>
<!--springcloud alibaba nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--springcloud alibaba sentinel-datasource-nacos 后续做持久化用到-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!--springcloud alibaba sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 编写配置文件
#yml配置
server:
port: 8401
spring:
application:
name: springcloudalibaba-sentinel-service
cloud:
nacos:
discovery:
#Nacos服务注册中心地址
server-addr: localhost:8848
sentinel:
transport:
#配置sentinel dashboard地址
dashboard: localhost:8080
#默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
port: 8719
management:
endpoints:
web:
exposure:
include: '*'
- 主启动类
/**
* @author cVzhanshi
* @create 2021-07-04 14:23
*/
@SpringBootApplication
@EnableDiscoveryClient
public class MainApp8401 {
public static void main(String[] args) {
SpringApplication.run(MainApp8401.class,args);
}
}
- 业务类
/**
* @author cVzhanshi
* @create 2021-07-04 14:26
*/
@RestController
public class FlowLimitController {
@GetMapping("/testA")
public String testA(){
return "--------testA";
}
@GetMapping("/testB")
public String testB(){
return "--------testB";
}
}
- 测试
- 启动nacos8848
- 启动Sentinel8080
- 启动微服务8401
- 打开sentinel控制台发现控制台空空如也
sentinel采用的是懒加载,需要执行一次请求才能在控制台显示监控的服务
- 访问一次请求后查看控制台
4.2 流控
4.2.1 基本介绍
- 资源名:唯一名称,默认请求路径
- 针对来源:Sentinel可以针对调用者 进行限流,填写微服务名,默认default (不区分来源)
- 阈值类型/单机阈值:
- QPS (每秒钟的请求数量) :当调用该api的QPS达到阈值的时候,进行限流
- 线程数:当调用该api的线程数达到阈值的时候,进行限流
- 是否集群:不需要集群,暂不研究
- 流控模式:
- 直接:api达到限流条件时,直接限流
- 关联:当关联的资源达到阈值时,就限流自己
- 链路:只记录指定链路上的流量(指定资源从入口资源进来的流量,如果达到阈值,就进行限流) [api级
别的针对来源]
- 流控效果:
- 快速失败:直接失败,抛异常.
- Warm Up:根据codeFactor (冷 加载因子,默认3)的值,从阈值/codeFactor, 经过预热时长,才达到设置的QPS阈值
- 排队等待:匀速排队,让请求以匀速的速度通过,阈值类型必须设置为QPS,否则无效
修改流控的地方
一、
二、
例如:
访问/testA,并刷新就会出现错误
4.2.2 流控模式
- 流控模式:
- 直接:api达到限流条件时,直接限流
- 关联:当关联的资源达到阈值时,就限流自己
- 链路:只记录指定链路上的流量(指定资源从入口资源进来的流量,如果达到阈值,就进行限流) [api级
别的针对来源]
直接
当资源访问达到阈值时就直接限流自己
关联
当关联的资源达到阈值时,就限流自己。类似于当与A关联的资源B达到阈值后,就限流A。
即,B惹事,A挂了
4.2.3 流控效果
- 流控效果:
- 快速失败:直接失败,抛异常.
- Warm Up:根据codeFactor (冷加载因子,默认3)的值,从阈值/codeFactor, 经过预热时长,才达到设置的QPS阈值
- 排队等待:匀速排队,让请求以匀速的速度通过,阈值类型必须设置为QPS,否则无效
快速失败
直接失败,抛出异常
Warm up
测试,新建流控规则
然后输入
http://localhost:8401/testA
,不停刷新,前5秒会限流,5秒后只要每秒不超过10个请求,就不会限流
排队等待
postman发起的每秒10个请求进行排队,testB每秒处理一个请求,请求都进行排队
4.3 降级
4.3.1 降级策略概述
Sentinel 提供以下几种熔断策略:
- 慢调用比例 (
SLOW_REQUEST_RATIO
):选择以慢调用比例作为阈值,需要设置允许的慢调用 RT(即最大的响应时间),请求的响应时间大于该值则统计为慢调用。当单位统计时长(statIntervalMs
)内请求数目大于设置的最小请求数目,并且慢调用的比例大于阈值,则接下来的熔断时长内请求会自动被熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求响应时间小于设置的慢调用 RT 则结束熔断,若大于设置的慢调用 RT 则会再次被熔断。 - 异常比例 (
ERROR_RATIO
):当单位统计时长(statIntervalMs
)内请求数目大于设置的最小请求数目,并且异常的比例大于阈值,则接下来的熔断时长内请求会自动被熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求成功完成(没有错误)则结束熔断,否则会再次被熔断。异常比率的阈值范围是[0.0, 1.0]
,代表 0% - 100%。 - 异常数 (
ERROR_COUNT
):当单位统计时长内的异常数目超过阈值之后会自动进行熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求成功完成(没有错误)则结束熔断,否则会再次被熔断。
Sentinel熔断降级会在调用链路中某个资源出现不稳定状态时(例如调用超时或异常比例升高),对这个资源的调用进行限制,让请求快速失败,避免影响到其它的资源而导致级联错误。
当资源被降级后,在接下来的降级时间窗口之内,对该资源的调用都自动熔断(默认行为是抛出DegradeException).
4.3.2 降级策略 RT( 慢调用比例 )
慢调用比例 (
SLOW_REQUEST_RATIO
):选择以慢调用比例作为阈值,需要设置允许的慢调用 RT(即最大的响应时间),请求的响应时间大于该值则统计为慢调用。当单位统计时长(statIntervalMs
)内请求数目大于设置的最小请求数目,并且慢调用的比例大于阈值,则接下来的熔断时长内请求会自动被熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求响应时间小于设置的慢调用 RT 则结束熔断,若大于设置的慢调用 RT 则会再次被熔断
测试
- 在controller中添加
@GetMapping("/testD")
public String testD() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("testD 测试RT");
return "----testD";
}
- 启动8401,在浏览器输入
http://localhost:8401/testD
,然后在sentinel设置testD降级规则
4.3.3 降级策略 异常比例
异常比例 (
ERROR_RATIO
):当单位统计时长(statIntervalMs
)内请求数目大于设置的最小请求数目,并且异常的比例大于阈值,则接下来的熔断时长内请求会自动被熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求成功完成(没有错误)则结束熔断,否则会再次被熔断。异常比率的阈值范围是[0.0, 1.0]
,代表 0% - 100%。
- 在controller中添加
@GetMapping("/testE")
public String testE() {
int age = 10 / 0; //百分百出错
System.out.println("testE 测试 异常比例");
return "----testD";
}
- 编辑降级规则
- 结果,刚开始第一次访问的时候回报错
- 继续范围,有异常的话会降级熔断
- 等设定的降级时间过去后又恢复了报错页面
4.3.4 降级策略 异常数
异常数 (
ERROR_COUNT
):当单位统计时长内的异常数目超过阈值之后会自动进行熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求成功完成(没有错误)则结束熔断,否则会再次被熔断。
同异常比例一样测试
- 有异常就降级熔断
4.4 热点参数限流
何为热点?热点即经常访问的数据。很多时候我们希望统计某个热点数据中访问频次最高的 Top K 数据,并对其访问进行限制。比如:
- 商品 ID 为参数,统计一段时间内最常购买的商品 ID 并进行限制
- 用户 ID 为参数,针对一段时间内频繁访问的用户 ID 进行限制
热点参数限流会统计传入参数中的热点参数,并根据配置的限流阈值与模式,对包含热点参数的资源调用进行限流。热点参数限流可以看做是一种特殊的流量控制,仅对包含热点参数的资源调用生效。
Sentinel 利用 LRU 策略统计最近最常访问的热点参数,结合令牌桶算法来进行参数级别的流控。热点参数限流支持集群模式。
兜底方法:分为系统默认和客户自定义两种,之前的case,限流出问题后,都是用sentinel系统默认的提示: Blocked by Sentinel (flow limiting)
我们能不能自定?类似hystrix,某个方法出问题了,就找对应的兜底降级方法?结论:从HystrixCommand到@SentinelResource
测试
- 在controller中添加代码:
@GetMapping("/testHotKey")
@SentinelResource(value = "testHotKey", blockHandler = "deal_testHotKey")
public String testHotKey(@RequestParam(value = "p1", required = false)String p1,
@RequestParam(value = "p2", required = false)String p2) {
return "----testHotKey";
}
//兜底方法
public String deal_testHotKey(String p1, String p2, BlockException exception) {
// sentinel的默认提示都是: Blocked by Sentinel (flow limiting)
return "----deal_testHotKey, o(╥﹏╥)o";
}
- 重启8401,浏览器输入
http://localhost:8401/testHotKey
,然后在后台对testHotKey进行热点规则配置
如果每秒的访问请求带有索引为0的参数的数量超过1,进入统计窗口期,然后调用兜底方法,1秒后退出统计窗口期,继续处理请求。
如果设置热点规则,而@SentinelResource注解里没有指明blockHandler兜底方法,就会把直接把错误页面信息打印到前台。
参数例外项
需求:我们期望p1参数当它是某个特殊值时,它的限流值和平时不一样。假如当p1的值等于5时,它的阈值可以达到200
配置:
给testHotKey方法添加
int i = 1 / 0;
异常。
然后重新测试,发现兜底方法不适用于异常,有异常会直接打印到页面。
结论:@SentinelResource主管配置出错,运行出错该走异常走异常
4.5 系统自适应限流
Sentinel 系统自适应限流从整体维度对应用入口流量进行控制,结合应用的 Load、CPU 使用率、总体平均 RT、入口 QPS 和并发线程数等几个维度的监控指标,通过自适应的流控策略,让系统的入口流量和系统的负载达到一个平衡,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。
- 保证系统不被拖垮
- 在系统稳定的前提下,保持系统的吞吐量
系统保护规则是应用整体维度的,而不是资源维度的,并且仅对入口流量生效。
- 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 达到阈值即触发系统保护。
测试
4.6 @SentinelResource
4.6.1 按资源名称限流+后续处理
测试
- 在8401pom中导入依赖
<dependency>
<groupId>cn.cvzhanshi</groupId>
<artifactId>springcloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
- 新建 RateLimitController
/**
* @author cVzhanshi
* @create 2021-07-10 16:04
*/
@RestController
public class RateLimitController {
@GetMapping("/byResource")
@SentinelResource(value = "byResource",blockHandler = "handleException")
public CommonResult byResource() {
return new CommonResult(200,"按照资源名称限流测试",new Payment(2020L,"serial001"));
}
//兜底方法
public CommonResult handleException(BlockException exception) {
return new CommonResult(444,exception.getClass().getCanonicalName() + "\t 服务不可用");
}
}
- 启动8401,访问
http://localhost:8401/byResource
- 对资源名新建流控
- 先单击访问
http://localhost:8401/byResource
,然后连续点击
其中,如果中间关闭8401模块,会发现Sentinel控制台的流控规则会消失,所以得出结论,流控规则是临时的
4.6.2 按照URL地址限流+后续处理
测试
- 在RateLimitController中添加代码
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl") //没有兜底方法,系统就用默认的
public CommonResult byUrl() {
return new CommonResult(200,"按照byUrl限流测试",new Payment(2020L,"serial002"));
}
- 启动8401,访问
http://localhost:8401/rateLimit/byUrl
- 新曾流控规则
- 继续访问
http://localhost:8401/rateLimit/byUrl
,先单击后连续访问
上面兜底方案面临的问题
- 系统默认的,没有体现我们自己的业务要求。
- 依照现有条件,我们自定义的处理方法又和业务代码耦合在- -块,不直观
- 每个业务方法都添加一个兜底的,那代码膨胀加剧。
- 全局统一的处理方法没有体现
所以出现了提供了客户自定义限流处理逻辑
4.6.3 客户自定义限流处理逻辑
- 创建CustomerBlockHandler类用于自定义限流处理逻辑
/**
* @author cVzhanshi
* @create 2021-07-10 16:16
*/
public class CustomerBlockHandler {
public static CommonResult handlerException(BlockException exception) {
return new CommonResult(444,"按照客户自定义限流测试,Glogal handlerException ---- 1");
}
public static CommonResult handlerException2(BlockException exception) {
return new CommonResult(444,"按照客户自定义限流测试,Glogal handlerException ---- 2");
}
}
- 在RateLimitController中添加代码
//CustomerBlockHandler
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handlerException2")
public CommonResult customerBlockHandler() {
return new CommonResult(200,"按照客户自定义限流测试",new Payment(2020L,"serial003"));
}
- 启动8401
http://localhost:8401/rateLimit/customerBlockHandler
- 配置流控规则,让兜底方法生效
说明:
4.7 服务熔断
4.7.1 Ribbon系列
4.7.1.1 测试环境的搭建
- 新建提供者模块springcloudalibaba-provider-payment9003,导入依赖
<dependencies>
<!-- SpringCloud ailibaba nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringCloud ailibaba sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- 引用自己定义的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>cn.cvzhanshi</groupId>
<artifactId>springcloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--监控-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 编写配置文件
server:
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
management:
endpoints:
web:
exposure:
include: '*' #监控
- 主启动类
/**
* @author cVzhanshi
* @create 2021-07-11 11:33
*/
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain9003.class,args);
}
}
- controller代码编写
/**
* @author cVzhanshi
* @create 2021-07-01 15:16
*/
@RestController
public class PaymentController {
@Value("${server.port}") //spring的注解
private String serverPort;
public static HashMap<Long, Payment> map = new HashMap<>();
static {
map.put(1L,new Payment(1L,"1111"));
map.put(2L,new Payment(2L,"2222"));
map.put(3L,new Payment(3L,"3333"));
}
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
Payment payment = map.get(id);
CommonResult<Payment> result = new CommonResult<>(200,"from mysql,serverPort: " + serverPort,payment);
return result;
}
}
- 新建模块9004按照9003一样
- 新建消费者模块springcloudalibaba-consumer-nacos-order84,导入依赖
<dependencies>
<!-- SpringCloud ailibaba nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringCloud ailibaba sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- 引用自己定义的api通用包,可以使用Payment支付Entity -->
<dependency>
<groupId>cn.cvzhanshi</groupId>
<artifactId>springcloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--监控-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 编写配置文件
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080 #sentinel
port: 8719
#消费者将要去访问的微服务名称(成功注册进nacos的微服务提供者),在这配置了访问的服务,业务类就不用在定义常量了
service-url:
nacos-user-service: http://nacos-payment-provider
- 主启动类
/**
* @author cVzhanshi
* @create 2021-07-11 12:00
*/
@SpringBootApplication
@EnableDiscoveryClient
public class OrderMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderMain84.class,args);
}
}
- config
/**
* @author cVzhanshi
* @create 2021-07-11 12:06
*/
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
- controller代码的编写
/**
* @author cVzhanshi
* @create 2021-07-11 12:01
*/
@RestController
@Slf4j
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
@SentinelResource(value = "fallback") //没有配置
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(
SERVICE_URL + "/paymentSQL/" + id, CommonResult.class,id);
if(id == 4){
throw new IllegalArgumentException("IllegalArgument,非法参数异常...");
}else if(result.getData() == null) {
throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
}
运行测试
- 启动Nacos
- 启动Sentinel
- 启动9003、9004
- 启动消费者84
- 连续访问localhost:84/consumer/fallback/1,会出现负载均衡的现象,9003、9004交替出现
- 分别访问localhost:84/consumer/fallback/4、localhost:84/consumer/fallback/5会出现错误页面
4.7.1.2 只配置fallback
- 修改消费者的controller
@RequestMapping("/consumer/fallback/{id}")
//@SentinelResource(value = "fallback") //没有配置
@SentinelResource(value = "fallback",fallback ="handlerFallback") //只配置fallback(只负责业务异常)
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(
SERVICE_URL + "/paymentSQL/" + id, CommonResult.class,id);
if(id == 4){
throw new IllegalArgumentException("IllegalArgument,非法参数异常...");
}else if(result.getData() == null) {
throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
//fallback兜底
public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult(444,"异常handlerFallback,exception内容: " + e.getMessage(), payment);
}
- 运行84模块,访问localhost:84/consumer/fallback/4或者localhost:84/consumer/fallback/5,不会出现错误页面,因为有fallback兜底方法
4.7.1.3 只配置blockHandler
- 修改消费者controller
@RequestMapping("/consumer/fallback/{id}")
//@SentinelResource(value = "fallback") //没有配置
//@SentinelResource(value = "fallback",fallback ="handlerFallback") //只配置fallback(只负责业务异常)
@SentinelResource(value = "fallback", blockHandler = "blockHandler") //只配置blockHandler(只负责sentinel控制台配置违规)
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(
SERVICE_URL + "/paymentSQL/" + id, CommonResult.class,id);
if(id == 4){
throw new IllegalArgumentException("IllegalArgument,非法参数异常...");
}else if(result.getData() == null) {
throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
//blockHandler兜底
public CommonResult blockHandler(@PathVariable Long id, BlockException e) {
Payment payment = new Payment(id,"null");
return new CommonResult(444,"blockHandler-sentinel 限流,BlockException: " + e.getMessage(), payment);
}
- 重启项目,访问
http://localhost:84/consumer/fallback/1
,然后在sentinel后台进行配置
- 继续快速访问
http://localhost:84/consumer/fallback/1
- 但是访问错误的url会出现错误页面,对用户不友好
因为没配置指定fallback兜底方法,所以会直接显示错误页面,配置了blockHandler兜底方法,所以当sentinel配置违规会执行blockHandler兜底方法
4.7.1.4 配置fallback和blockHandler
- 修改@SentinelResource注解
@SentinelResource(value = "fallback",
fallback ="handlerFallback",
blockHandler = "blockHandler")
- 重启项目,访问
http://localhost:84/consumer/fallback/1
,然后在sentinel后台进行配置
- 访问
http://localhost:84/consumer/fallback/1
多次刷新执行blockHandler兜底方法
- 访问
http://localhost:84/consumer/fallback/5
执行fallback兜底方法
当@SentinelResource注解fallback和blockHandler都指定后,然后同时符合,优先执行blockHandler兜底方法
4.7.1.5 忽略属性
- 修改@SentinelResource注解
@SentinelResource(value = "fallback",
fallback ="handlerFallback",
blockHandler = "blockHandler",
exceptionsToIgnore = {IllegalArgumentException.class})
- 运行访问
http://localhost:84/consumer/fallback/4
- 运行访问 localhost:84/consumer/fallback/5
说明IllegalArgumentException异常被忽略了
4.7.2 Feign系列
- 在84模块的基础上添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 修改配置文件
#激活Sentinel对Feign的支持
feign:
sentinel:
enabled: true
- 主启动类上添加
@EnableFeignClients
- 创建service层,创建PaymentService接口
/**
* @author cVzhanshi
* @create 2021-07-11 17:53
*/
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService {
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}
- 创建fallback类实现PaymentService
/**
* @author cVzhanshi
* @create 2021-07-11 17:59
*/
@Component
public class PaymentFallbackService implements PaymentService {
@Override
public CommonResult<Payment> paymentSQL(Long id) {
return new CommonResult<>(444,"服务降级返回,---PaymentFallbackService",new Payment(id,"ErrorSerial"));
}
}
- 修改CircleBreakerController
@Resource
private PaymentService paymentService;
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult< Payment > paymentSQL(@PathVariable("id") Long id){
return paymentService.paymentSQL(id);
}
- 测试
- 启动nacos、sentinel、9003、9004、84
- 访问http://localhost:84/consumer/paymentSQL/1
- 关闭9003、9004访问http://localhost:84/consumer/paymentSQL/1
4.7.3 熔断限流框架对比
4.8 Sentinel持久化规则
一旦我们重启应用, sentinel规则将消失,生产环境需要将配置规则进行持久化
持久化:将限流配置规则持久化进Nacos保存,只要刷新8401某个rest地址,sentinel控制台
的流控规则就能看到,只要Nacos里面的配置不删除,针对8401.上sentinel.上的流控规则持续有效
测试 修改8401
- 添加持久化需要的依赖
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
- 修改配置文件
#yml配置
server:
port: 8401
spring:
application:
name: springcloudalibaba-sentinel-service
cloud:
nacos:
discovery:
#Nacos服务注册中心地址
server-addr: localhost:8848
sentinel:
transport:
#配置sentinel dashboard地址
dashboard: localhost:8080
#默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
port: 8719
datasource:
ds1:
nacos:
server-addr: localhost:8848 #nacos
dataId: ${spring.application.name}
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
management:
endpoints:
web:
exposure:
include: '*'
feign:
sentinel:
enabled: true #激活Sentinel 对Feign的支持
其中可能会因为jdk版本问题报错,修改jdk版本即可
- 在nacos中添加配置
- 启动8401
http://localhost:8401/rateLimit/byUrl
多次刷新
- 停止8401
- 再次启动8401,因为sentinel是懒加载模式,所以需要先访
http://localhost:8401/rateLimit/byUrl
,然后查看sentinel后台
实现了sentinel配置的持久化