前言:
Sentinel干嘛用的,我们先通过几个问题点,再通过这个几个问题点来看Sentinel是干嘛用的。
限流:
限流,字眼上的意思就是限制流量(请求数等),就是打个比方:一桶水最多装50毫升以每秒不超过10毫升,就不会溢出,假设瞬间你的水龙头滴水量超过了10毫升,那桶就会溢出,可能比较慢,但是如果一秒20毫升的水滴入,那很快就溢出了。可能一瞬间,也可能慢慢叠加。
在系统上如果你的系统最大支持1000/qps,那如果一秒只有1000的qps进来,那服务器能稳定运行,如果一秒2000/qps的进来,服务器扛不住,扛不住就挂了,挂了没法提供对外服务导致业务直接熔断。如果算上1个请求的执行时间超过1秒,那可能不达到1000/qps也会扛不住。
限流的意义在于限制
如:服务器只有支撑1000QPS的处理能力,那就每秒放1000个请求,自然保证了服务器的稳定,这就是限流。
熔断降级:
在分布式系统中,如:一个下单接口,它调了一个接口,如时间太长未响应等问题,那肯定会拖垮核心服务,直接把当前这个服务给熔断掉。
由于调用关系的复杂性,如果调用链路中的某个资源不稳定,最终会导致请求发生堆积。Sentinel 熔断降级会在调用链路中某个资源出现不稳定状态时(例如调用超时或异常比例升高),对这个资源的调用进行限制,让请求快速失败,避免影响到其它的资源而导致级联错误。当资源被降级后,在接下来的降级时间窗口之内,对该资源的调用都自动熔断
附:ratelimter也可以用做限流,可自行研究
简述:
Sentinel主要限流、熔断降级,系统负载保护等多个维度来保障服务之间的稳定性
进入正文,接下来我们就以Springboot+sentinel来做一个限流的demo
一:创建springboot项目
这里只贴相关依赖和截图
1.1:基础代码
pom.xml
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
<sentinel.version>1.8.0</sentinel.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Sentinel -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>${
sentinel.version}</version>
</dependency>
<!-- Sentinel注解 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>${
sentinel.version}</version>
</dependency>
<!-- 控制台通信的jar包 客户端 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>${
sentinel.version}</version>