Spring Cloud Alibaba Sentinel集成Spring Cloud Gateway

653 阅读6分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第22天,点击查看活动详情

Sentinel 支持对 Spring Cloud Gateway、Zuul 等主流的 API Gateway 进行限流。 sentinel-api-gateway-common-arch

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 分组维度进行限流。

集成Spring Cloud Gateway

关于Spring Cloud Gateway这里就不做过多介绍,可以看我之前的文章springcloud 入门 之网关 springcloud gateway

集成入门

  1. 新建一个springboot项目模块cloud_gateway

若想跟 Sentinel Starter 配合使用,需要加上 spring-cloud-alibaba-sentinel-gateway 依赖,同时需要添加 spring-cloud-starter-gateway 依赖来让 spring-cloud-alibaba-sentinel-gateway 模块里的 Spring Cloud Gateway 自动化配置类生效,cloud_gateway模块引入依赖:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  1. 修改配置文件
server.port=8086

# 应用名
spring.application.name=SentinelCloudGateway
# spring cloud gateway 采用的是netty+webflux
spring.main.web-application-type=reactive

spring.cloud.sentinel.filter.enabled=false

spring.cloud.sentinel.log.dir=D:\\software\\sentinel

#禁止懒加载
spring.cloud.sentinel.eager=true
spring.cloud.sentinel.transport.port=8719
# dashboard 地址
spring.cloud.sentinel.transport.dashboard=127.0.0.1:8080

spring.cloud.sentinel.scg.fallback.content-type=application/json
spring.cloud.sentinel.scg.fallback.mode=redirect
spring.cloud.sentinel.scg.fallback.response-status=429
# 限流时重定向的链接
spring.cloud.sentinel.scg.fallback.redirect=https://www.baidu.com/

# 路由配置
spring.cloud.gateway.routes[0].id=nacos_provider
spring.cloud.gateway.routes[0].uri=http://localhost:8090
spring.cloud.gateway.routes[0].predicates[0]=Path=/helloProvider/**

配置解释:

  • 如果项目中引入了 spring-boot-starter-web依赖, spring.main.web-application-type=reactive 这个配置一定要加上,因为Spring Cloud Gateway是使用netty+webflux方式实现的,跟spring-boot-starter-web冲突,启动时会报错。

  • spring.cloud.sentinel.scg开头的配置是sentinel集成Spring Cloud Gateway后的配置,这段配置一定要有。

  • spring.cloud.sentinel.scg.fallback.mode:fallback模式,一共有两种模式可选: redirectresponse

  • spring.cloud.sentinel.scg.fallback.redirect:限流后的跳转的链接,只有在redirect模式下有用。response 模式下可以配置 spring.cloud.sentinel.scg.fallback.response-body 做为响应体

  • 路由配置nacos_provider是启动的另一个服务,用于流控测试,它的端口号是8089,同时在nacos_provider服务中有个ProviderHelloController类:

@RequestMapping("/helloProvider")
@RestController
public class ProviderHelloController {

    @GetMapping("/hello/{param}")
    public String hello(@PathVariable("param") String param){
        return "hello,"+param+".this is nacos provider";
    }
}
  1. 测试

启动sentinel-dashboard

java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar

再分别启动cloud_gateway和nacos_provider服务

访问http://localhost:8080/ ,登录sentinel-dashboard

Img

可以看到多了一个菜单 API 分组管理,这就表明 Sentinel集成Spring Cloud Gateway成功。

浏览器访问 http://localhost:8090/helloProvider/hello/ncaco ,可以看到nacos_provider服务接口调用成功。

Img

然后再访问 http://localhost:8086/helloProvider/hello/sentinel%20gateway

Img

这说明Spring Cloud Gateway也是可以正常使用的。

网关限流规则

从 1.6.0 版本开始,Sentinel 提供了 Spring Cloud Gateway 的适配模块,可以提供两种资源维度的限流:

  • route 维度:即在 Spring 配置文件中配置的路由条目,资源名为对应的 routeId
  • 自定义 API 维度:用户可以利用 Sentinel 提供的 API 来自定义一些 API 分组

其中网关限流规则 GatewayFlowRule 的字段解释如下:

  • resource:资源名称,可以是网关中的 route 名称或者用户自定义的 API 分组名称。
  • resourceMode:规则是针对 API Gateway 的 route(RESOURCE_MODE_ROUTE_ID)还是用户在 Sentinel 中定义的 API 分组(RESOURCE_MODE_CUSTOM_API_NAME),默认是 route。
  • grade:限流指标维度,同限流规则的 grade 字段。
  • count:限流阈值
  • intervalSec:统计时间窗口,单位是秒,默认是 1 秒。
  • controlBehavior:流量整形的控制效果,同限流规则的 controlBehavior 字段,目前支持快速失败和匀速排队两种模式,默认是快速失败。
  • burst:应对突发请求时额外允许的请求数目。
  • maxQueueingTimeoutMs:匀速排队模式下的最长排队时间,单位是毫秒,仅在匀速排队模式下生效。
  • paramItem:参数限流配置。若不提供,则代表不针对参数进行限流,该网关规则将会被转换成普通流控规则;否则会转换成热点规则。其中的字段:
    • parseStrategy:从请求中提取参数的策略,目前支持提取来源 IP(PARAM_PARSE_STRATEGY_CLIENT_IP)、Host(PARAM_PARSE_STRATEGY_HOST)、任意 Header(PARAM_PARSE_STRATEGY_HEADER)和任意 URL 参数(PARAM_PARSE_STRATEGY_URL_PARAM)四种模式。
    • fieldName:若提取策略选择 Header 模式或 URL 参数模式,则需要指定对应的 header 名称或 URL 参数名称。
    • pattern:参数值的匹配模式,只有匹配该模式的请求属性值会纳入统计和流控;若为空则统计该请求属性的所有值。(1.6.2 版本开始支持)
    • matchStrategy:参数值的匹配策略,目前支持精确匹配(PARAM_MATCH_STRATEGY_EXACT)、子串匹配(PARAM_MATCH_STRATEGY_CONTAINS)和正则匹配(PARAM_MATCH_STRATEGY_REGEX)。(1.6.2 版本开始支持)

用户可以通过 GatewayRuleManager.loadRules(rules) 手动加载网关规则,或通过 GatewayRuleManager.register2Property(property) 注册动态规则源动态推送(推荐方式)。

route 维度限流

在流控规则中新增流控规则:

Img

API类型选择Route ID,API名称选择在配置文件中配置的spring cloud gateway 路由id nacos_provider

浏览器多刷新几次链接http://localhost:8086/helloProvider/hello/sentinel ,就可以看到跳转到www.baidu.com/

API分组流控

API分组流控需要两步配置:

  1. API 分组管理添加API组

Img

API名称根据需要自定义

匹配模式有3种:

  • 精确:需要指定完整的API路径名
  • 前缀:指定API路径前缀,跟spring cloud gateway配置的断言路径一样,比如:/helloProvider/**
  • 正则:按照正则表达式来匹配API
  1. 配置流控规则

Img

跟route 维度限流不同的是,API类型要选择API 分组,API名称要选择API分组管理中定义的API名称

访问链接http://localhost:8086/helloProvider/hello/sentinel ,多刷新几次就能看到效果

网关流控实现原理

当通过 GatewayRuleManager 加载网关流控规则(GatewayFlowRule)时,无论是否针对请求属性进行限流,Sentinel 底层都会将网关流控规则转化为热点参数规则(ParamFlowRule),存储在 GatewayRuleManager 中,与正常的热点参数规则相隔离。转换时 Sentinel 会根据请求属性配置,为网关流控规则设置参数索引(idx),并同步到生成的热点参数规则中。

外部请求进入 API Gateway 时会经过 Sentinel 实现的 filter,其中会依次进行 路由/API 分组匹配请求属性解析参数组装。Sentinel 会根据配置的网关流控规则来解析请求属性,并依照参数索引顺序组装参数数组,最终传入 SphU.entry(res, args) 中。Sentinel API Gateway Adapter Common 模块向 Slot Chain 中添加了一个 GatewayFlowSlot,专门用来做网关规则的检查。GatewayFlowSlot 会从 GatewayRuleManager 中提取生成的热点参数规则,根据传入的参数依次进行规则检查。若某条规则不针对请求属性,则会在参数最后一个位置置入预设的常量,达到普通流控的效果。

image

总结

本篇文章我们只是简单的介绍和使用了 Sentinel集成Spring Cloud Gateway,算是对 Sentinel网关限流有了一个简单的了解,感兴趣的可以深入了解一下。

参考资料:

github.com/alibaba/Sen…