Sentinel 支持对 Spring Cloud Gateway、Zuul 等主流的 API Gateway 进行限流。
从 1.6.0 版本开始,Sentinel 提供了 Spring Cloud Gateway 的适配模块,可以提供两种资源维度的限流:
route 维度:即在 Spring 配置文件中配置的路由条目,资源名为对应的 routeId
自定义 API 维度:用户可以利用 Sentinel 提供的 API 来自定义一些 API 分组
Sentinel 1.6.0 引入了 Sentinel API Gateway Adapter Common 模块,此模块中包含网关限流的规则和自定义 API 的实体和管理逻辑:
GatewayFlowRule :网关限流规则,针对 API Gateway 的场景定制的限流规则,可以针对不同
route 或自定义的 API 分组进行限流,支持针对请求中的参数、Header、来源 IP 等进行定制化的
限流。
ApiDefinition :用户自定义的 API 定义分组,可以看做是一些 URL 匹配的组合。比如我们可以
定义一个 API 叫 my_api ,请求 path 模式为 /foo/** 和 /baz/** 的都归到 my_api 这个 API
分组下面。限流的时候可以针对这个自定义的 API 分组维度进行限流。
1、环境搭建
导入Sentinel 的响应依赖
<!--sentinel限流-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
<version>1.6.3</version>
</dependency>
2、编写配置类
注意:此时要注释掉之前在yml中配置的filter的限流方式:
server:
port: 8080 #端口
spring:
application:
name: api-gateway-server #服务名称
redis:
host: localhost
pool: 6379
database: 0
cloud: #配置SpringCloudGateway的路由
gateway:
discovery:
locator:
enabled: true #开启根据微服务名称自动转发
lower-case-service-id: true #微服务名称以小写形式呈现
routes:
- id: order-service
uri: lb://service-order
predicates:
- Path=/order-service/**
filters:
- RewritePath=/order-service/(?<segment>.*), /$\{
segment}
- id: product-service
uri: lb://service-product
predicates:
- Path=/product-service/**