一、什么是网关限流:
在微服务架构中,网关层可以屏蔽外部服务直接对内部服务进行调用,对内部服务起到隔离保护的作用,网关限流,顾名思义,就是通过网关层对服务进行限流,从而达到保护后端服务的作用。
Sentinel 从 1.6.0 版本开始就提供了 Spring Cloud Gateway 的适配,可以提供两种资源维度的限流:
- route维度:即在配置文件中配置的路由条目,资源名为对应的 routeId,这种属于粗粒度的限流,一般是对某个微服务进行限流。
- 自定义API维度:用户可以利用 Sentinel 提供的API来自定义一些API分组,这种属于细粒度的限流,针对某一类的uri进行匹配限流,可以跨多个微服务。
二、gateway 整合 sentinel 实现网关限流:
那么接下来我们就介绍下 spring cloud gateway 如何整合 sentinel,至于如何搭建网关项目和整合nacos注册中心上篇文章我们已经介绍过了,感兴趣的读者请阅读这篇文章:Spring Cloud Gateway 服务网关的部署与使用详细介绍
1、添加 sentinel 相关依赖:
<!-- 引入sentinel进行服务降级熔断 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- gateway网关整合sentinel进行限流降级 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
2、配置文件中添加 sentinel 控制台的配置:
# sentinel看板相关配置
spring.cloud.sentinel.eager = true
spring.cloud.sentinel.transport.dashboard = 172.28.190.101:8999
3、启动网关项目:
对于网关项目,我们需要在原启动参数的基础上添加如下启动参数,标记该应用为 API Gateway 类型:
# 注:通过 Spring Cloud Alibaba Sentinel 自动接入的 API Gateway 整合则无需此参数
-Dcsp.sentinel.app.type=1
4、访问 sentinel 控制台:
至此,我们就已经将 Spring Cloud Gateway 与 Sentinel 整合好了,进入 sentinel 控制台就能够看到网关项目被监控了
三、sentinel 网关流控规则的介绍:
整合好 Spring Cloud Gateway 与 Sentinel 之后,接下来我们介绍下如何基于 sentinel-dashboard 控制台进行网关流控,如下图所示: