• 【微服务】Sentinel 适配网关进行流量控制


    博主介绍:✌全网粉丝5W,全栈开发工程师,从事多年软件开发,在大厂呆过。持有软件中级、六级等证书。可提供微服务项目搭建与毕业项目实战,博主也曾写过优秀论文,查重率极低,在这方面有丰富的经验✌

    博主作品:《Java项目案例》主要基于SpringBoot+MyBatis/MyBatis-plus+MySQL+Vue等前后端分离项目,可以在左边的分类专栏找到更多项目。《Uniapp项目案例》有几个有uniapp教程,企业实战开发。《微服务实战》专栏是本人的实战经验总结,《Spring家族及微服务系列》专注Spring、SpringMVC、SpringBoot、SpringCloud系列、Nacos等源码解读、热门面试题、架构设计等。除此之外还有不少文章等你来细细品味,更多惊喜等着你哦

    🍅uniapp微信小程序🍅面试题软考题免费使用,还可以使用ChatGPT,微信支付,扫码加群

    点击这里预览

    🍅开源项目免费哦(有vue2与vue3版本): 点击这里克隆或者下载🍅

    🍅文末获取联系🍅精彩专栏推荐订阅👇🏻👇🏻 不然下次找不到哟

    Java项目案例《100套》

    https://blog.csdn.net/qq_57756904/category_12173599.html

    uniapp小程序《100套》
    https://blog.csdn.net/qq_57756904/category_12199600.html

    SpringCloud微服务第1章

    SpringCloud微服务第2章

    SpringCloud Alibaba系列以及要点

    目录

    一、前言

    二、Sentinel适配Spring Cloud Gateway

    1、使用时需引入以下模块(以 Maven 为例):

    1.1、Spring Cloud Gateway 中配置以下路由

    1.2、自定义一些 API 分组

    三、Sentinel 适配Zuul 1.x

    1、使用时需引入以下模块(以 Maven 为例):

    2、配置过滤器Bean

    3、发生限流之后的处理流程 

    3.1、自定义 FallbackProvider 

    四、Sentinel 适配Zuul 2.x

    1、使用时需引入以下模块(以 Maven 为例):

    五、网关流控实现原理

    六、网关流控控制台


    一、前言

    Sentinel 支持对 Spring Cloud Gateway、Zuul 等主流的 API Gateway 进行限流。

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

    其中网关限流规则 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) 注册动态规则源动态推送推荐方式)。

    二、Sentinel适配Spring Cloud Gateway

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

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

    1、使用时需引入以下模块(以 Maven 为例):

    1. <dependency>
    2. <groupId>com.alibaba.cspgroupId>
    3. <artifactId>sentinel-spring-cloud-gateway-adapterartifactId>
    4. <version>x.y.zversion>
    5. dependency>

    使用时只需注入对应的 SentinelGatewayFilter 实例以及 SentinelGatewayBlockExceptionHandler 实例即可。比如:

    1. @Configuration
    2. public class GatewayConfiguration {
    3. private final List viewResolvers;
    4. private final ServerCodecConfigurer serverCodecConfigurer;
    5. public GatewayConfiguration(ObjectProvider> viewResolversProvider,
    6. ServerCodecConfigurer serverCodecConfigurer) {
    7. this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
    8. this.serverCodecConfigurer = serverCodecConfigurer;
    9. }
    10. @Bean
    11. @Order(Ordered.HIGHEST_PRECEDENCE)
    12. public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
    13. // Register the block exception handler for Spring Cloud Gateway.
    14. return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    15. }
    16. @Bean
    17. @Order(-1)
    18. public GlobalFilter sentinelGatewayFilter() {
    19. return new SentinelGatewayFilter();
    20. }
    21. }

    1.1、Spring Cloud Gateway 中配置以下路由

    1. server:
    2. port: 8090
    3. spring:
    4. application:
    5. name: spring-cloud-gateway
    6. cloud:
    7. gateway:
    8. enabled: true
    9. discovery:
    10. locator:
    11. lower-case-service-id: true
    12. routes:
    13. # Add your routes here.
    14. - id: product_route
    15. uri: lb://product
    16. predicates:
    17. - Path=/product/**
    18. - id: httpbin_route
    19. uri: https://httpbin.org
    20. predicates:
    21. - Path=/httpbin/**
    22. filters:
    23. - RewritePath=/httpbin/(?.*), /$\{segment}

    1.2、自定义一些 API 分组

    1. private void initCustomizedApis() {
    2. Set definitions = new HashSet<>();
    3. ApiDefinition api1 = new ApiDefinition("some_customized_api")
    4. .setPredicateItems(new HashSet() {{
    5. add(new ApiPathPredicateItem().setPattern("/product/baz"));
    6. add(new ApiPathPredicateItem().setPattern("/product/foo/**")
    7. .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_PREFIX));
    8. }});
    9. ApiDefinition api2 = new ApiDefinition("another_customized_api")
    10. .setPredicateItems(new HashSet() {{
    11. add(new ApiPathPredicateItem().setPattern("/ahas"));
    12. }});
    13. definitions.add(api1);
    14. definitions.add(api2);
    15. GatewayApiDefinitionManager.loadApiDefinitions(definitions);
    16. }

    那么这里面的 route ID(如 product_route)和 API name(如 some_customized_api)都会被标识为 Sentinel 的资源。比如访问网关的 URL 为 http://localhost:8090/product/foo/22 的时候,对应的统计会加到 product_route 和 some_customized_api 这两个资源上面,而 http://localhost:8090/httpbin/json 只会对应到 httpbin_route 资源上面。

    注意:有的时候 Spring Cloud Gateway 会自己在 route 名称前面拼一个前缀,如 ReactiveCompositeDiscoveryClient_xxx 这种。请观察簇点链路页面实际的资源名。

    可以在 GatewayCallbackManager 注册回调进行定制:

    • setBlockHandler注册函数用于实现自定义的逻辑处理被限流的请求,对应接口为 BlockRequestHandler默认实现为 DefaultBlockRequestHandler,当被限流时会返回类似于下面的错误信息:Blocked by Sentinel: FlowException

    注意

    • Sentinel 网关流控默认的粒度是 route 维度以及自定义 API 分组维度,默认不支持 URL 粒度。若通过 Spring Cloud Alibaba 接入,将 spring.cloud.sentinel.filter.enabled 配置项置为 false(若在网关流控控制台上看到了 URL 资源,就是此配置项没有置为 false)。
    • 若使用 Spring Cloud Alibaba Sentinel 数据源模块,需要注意网关流控规则数据源类型是 gw-flow,若将网关流控规则数据源指定为 flow 则不生效

    三、Sentinel 适配Zuul 1.x

    Sentinel 提供了 Zuul 1.x 的适配模块,可以为 Zuul Gateway 提供两种资源维度的限流:

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

    1、使用时需引入以下模块(以 Maven 为例):

    1. <dependency>
    2. <groupId>com.alibaba.cspgroupId>
    3. <artifactId>sentinel-zuul-adapterartifactId>
    4. <version>x.y.zversion>
    5. dependency>

    2、配置过滤器Bean

    若使用的是 Spring Cloud Netflix Zuul,可以直接在配置类中将三个 filter 注入到 Spring 环境中即可:

    1. @Configuration
    2. public class ZuulConfig {
    3. @Bean
    4. public ZuulFilter sentinelZuulPreFilter() {
    5. // We can also provider the filter order in the constructor.
    6. return new SentinelZuulPreFilter();
    7. }
    8. @Bean
    9. public ZuulFilter sentinelZuulPostFilter() {
    10. return new SentinelZuulPostFilter();
    11. }
    12. @Bean
    13. public ZuulFilter sentinelZuulErrorFilter() {
    14. return new SentinelZuulErrorFilter();
    15. }
    16. }

    Sentinel Zuul Adapter 生成的调用链路类似于下面,其中的资源名都是 route ID 或者自定义的 API 分组名称:

    1. -EntranceNode: sentinel_gateway_context$$route$$another-route-b(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:8 1mb:1 1mt:9)
    2. --another-route-b(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:4 1mb:1 1mt:5)
    3. --another_customized_api(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:4 1mb:0 1mt:4)
    4. -EntranceNode: sentinel_gateway_context$$route$$my-route-1(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:6 1mb:0 1mt:6)
    5. --my-route-1(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:2 1mb:0 1mt:2)
    6. --some_customized_api(t:0 pq:0.0 bq:0.0 tq:0.0 rt:0.0 prq:0.0 1mp:2 1mb:0 1mt:2)

    3、发生限流之后的处理流程 

    • 发生限流之后可自定义返回参数,通过实现 SentinelFallbackProvider 接口,默认的实现是 DefaultBlockFallbackProvider
    • 默认的 fallback route 的规则是 route ID 自定义的 API 分组名称

    3.1、自定义 FallbackProvider 

    1. // 自定义 FallbackProvider
    2. public class MyBlockFallbackProvider implements ZuulBlockFallbackProvider {
    3. private Logger logger = LoggerFactory.getLogger(DefaultBlockFallbackProvider.class);
    4. // you can define route as service level
    5. @Override
    6. public String getRoute() {
    7. return "/book/app";
    8. }
    9. @Override
    10. public BlockResponse fallbackResponse(String route, Throwable cause) {
    11. RecordLog.info(String.format("[Sentinel DefaultBlockFallbackProvider] Run fallback route: %s", route));
    12. if (cause instanceof BlockException) {
    13. return new BlockResponse(429, "Sentinel block exception", route);
    14. } else {
    15. return new BlockResponse(500, "System Error", route);
    16. }
    17. }
    18. }
    19. // 注册 FallbackProvider
    20. ZuulBlockFallbackManager.registerProvider(new MyBlockFallbackProvider());

    限流发生之后的默认返回:

    1. {
    2. "code":429,
    3. "message":"Sentinel block exception",
    4. "route":"/"
    5. }

    注意

    • Sentinel 网关流控默认的粒度是 route 维度以及自定义 API 分组维度,默认不支持 URL 粒度。若通过 Spring Cloud Alibaba 接入,请将 spring.cloud.sentinel.filter.enabled 配置项置为 false(若在网关流控控制台上看到了 URL 资源,就是此配置项没有置为 false)。
    • 若使用 Spring Cloud Alibaba Sentinel 数据源模块,需要注意网关流控规则数据源类型是 gw-flow若将网关流控规则数据源指定为 flow 则不生效

    四、Sentinel 适配Zuul 2.x

    注:从 1.7.2 版本开始支持,需要 Java 8 及以上版本。

    Sentinel 提供了 Zuul 2.x 的适配模块,可以为 Zuul Gateway 提供两种资源维度的限流:

    • route 维度:对应 SessionContext 中的 routeVIP
    • 自定义 API 维度:用户可以利用 Sentinel 提供的 API 来自定义一些 API 分组

    1、使用时需引入以下模块(以 Maven 为例):

    1. <dependency>
    2. <groupId>com.alibaba.cspgroupId>
    3. <artifactId>sentinel-zuul2-adapterartifactId>
    4. <version>x.y.zversion>
    5. dependency>

    然后配置对应的 filter 即可:

    1. filterMultibinder.addBinding().toInstance(new SentinelZuulInboundFilter(500));
    2. filterMultibinder.addBinding().toInstance(new SentinelZuulOutboundFilter(500));
    3. filterMultibinder.addBinding().toInstance(new SentinelZuulEndpoint());

    五、网关流控实现原理

    当通过 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 中提取生成的热点参数规则,根据传入的参数依次进行规则检查。若某条规则不针对请求属性,则会在参数最后一个位置置入预设的常量,达到普通流控的效果。

    六、网关流控控制台

    Sentinel 1.6.3 引入了网关流控控制台的支持,可以直接在 Sentinel 控制台上查看 API Gateway 实时的 route 和自定义 API 分组监控,管理网关规则和 API 分组配置。

    在 API Gateway 端,只需要在原有启动参数的基础上添加如下启动参数即可标记应用为 API Gateway 类型:

    1. # 注:通过 Spring Cloud Alibaba Sentinel 自动接入的 API Gateway 整合则无需此参数
    2. -Dcsp.sentinel.app.type=1

    添加正确的启动参数并有访问量后,就可以在 Sentinel 上面看到对应的 API Gateway 了。可以查看实时的 route 和自定义 API 分组的监控和调用信息:

    可以在控制台配置自定义的 API 分组,将一些 URL 匹配模式归为一个 API 分组:

    然后可以在控制台针对预设的 route ID 或自定义的 API 分组配置网关流控规则:

    这些都是Sentinel 适配网关流量控制的内容。

  • 相关阅读:
    uniapp sqlite时在无法读取到已准备好数据的db文件中的数据
    【八股文】五分钟掌握类加载过程
    C# pythonnet(1)_传感器数据清洗算法
    救济金发放(The Dole Queue, UVa 133)rust解法
    根据ip及子网掩码得出网段
    redis的详细介绍与操作命令
    Spring原理:Mybatis整合原理
    HCIE-灾备技术和安全服务
    【SA8295P 源码分析 (一)】02 - SA8295P 的 LUN 及 分区表 配置详解
    基于微信中介看房预约小程序系统设计与实现 开题报告
  • 原文地址:https://blog.csdn.net/qq_57756904/article/details/127763081