这是我参与更文挑战的第 18 天,活动详情查看: 更文挑战
Sentinel
一、概述
https://sentinelguard.io/zh-cn/docs/introduction.html
https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D
和之前的Hystrix功能相同。
二、环境配置
下载安装
- 下载地址:
https://github.com/alibaba/Sentinel/releases - 启动:
java -jar sentinel-dashboard-1.7.0.jar - 访问:
http://localhost:8080,账号密码sentinel
初始化监控
-
新建
cloudalibaba-sentinel-service8401 -
依赖:
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <!--持久化用--> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-nacos</artifactId> </dependency> -
配置:
server: port: 8401 spring: application: name: cloudalibaba-sentinel-service cloud: nacos: discovery: server-addr: localhost:8848 # nacos配置中心地址 sentinel: transport: dashboard: localhost:8080 # 默认8719端口,如果被占用自动从8719开始一次+1扫描,找到未被占用的端口 port: 8719 management: # 暴露监控地址 endpoints: web: exposure: include: '*' -
controller
@RestController public class FlowLimitController { @GetMapping("/testA") public String testA() { return "testA"; } @GetMapping("/testB") public String testB() { return "testB"; } } -
因为sentinel是懒加载机制,所以启动服务后不会立刻显示服务,需要先访问一次才会监控到。
三、Sentinel流控
概述
https://sentinelguard.io/zh-cn/docs/flow-control.html
添加流控
在sentinel主界面配置针对具体请求做流控
阈值类型
- QPS(每秒请求数)限流:当前配置对/testA请求做限流,只允许每秒指定次的访问,超过后直接访问失败,给出系统默认的提示。
- 线程数限流:可以接收多个请求,但是同时只能相应指定数量的请求,其余请求给出失败提示。
流控模式
- 直接:API达到限流条件时就直接限流
- 关联:当关联的资源达到限流条件时就限流自己
- 链路:只记录指定链路上的流量。(指定资源从入口资源来的流量,达到阈值进行限流)
流控效果
- 快速失败:直接失败,抛出异常。
- Warm Up(预热):
- 该方式主要用于系统长期处于低水位的情况下,当流量突然增加时,直接把系统拉升到高水位可能瞬间把系统压垮。通过"冷启动",让通过的流量缓慢增加,在一定时间内逐渐增加到阈值上限,给冷系统一个预热的时间,避免冷系统被压垮的情况。
- 公式:阈值除于coldFactor(冷加载因子,默认为3),经过预热时长后才会到达阈值。
- 例子:当前阈值为10,预热时长5,因为coldFactor的存在,所以一开始的阈值为3,当预热时长过去后阈值才会到10。
- 排队等待:匀速排队,严格控制请求通过的时间间隔,阈值必须设置为QPS