Sentinel整合Spring Cloud Gateway、Zuul详解

简介: Sentinel整合Spring Cloud Gateway、Zuul详解

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) 注册动态规则源动态推送(推荐方式)。

          Spring Cloud Gateway

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

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

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

            <dependency>

               <groupId>com.alibaba.csp</groupId>

               <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>

               <version>x.y.z</version>

            </dependency>

            使用时只需注入对应的 SentinelGatewayFilter 实例以及 SentinelGatewayBlockExceptionHandler 实例即可(若使用了 Spring Cloud Alibaba Sentinel,则只需按照文档进行配置即可,无需自己加 Configuration)。比如:

            @Configuration
            public class GatewayConfiguration {
                private final List<ViewResolver> viewResolvers;
                private final ServerCodecConfigurer serverCodecConfigurer;
                public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                            ServerCodecConfigurer serverCodecConfigurer) {
                    this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
                    this.serverCodecConfigurer = serverCodecConfigurer;
                }
                @Bean
                @Order(Ordered.HIGHEST_PRECEDENCE)
                public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
                    // Register the block exception handler for Spring Cloud Gateway.
                    return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
                }
                @Bean
                @Order(Ordered.HIGHEST_PRECEDENCE)
                public GlobalFilter sentinelGatewayFilter() {
                    return new SentinelGatewayFilter();
                }
            }

            image.gif

            Demo 示例:sentinel-demo-spring-cloud-gateway

            比如我们在 Spring Cloud Gateway 中配置了以下路由:

            server:
              port: 8090
            spring:
              application:
                name: spring-cloud-gateway
              cloud:
                gateway:
                  enabled: true
                  discovery:
                    locator:
                      lower-case-service-id: true
                  routes:
                    # Add your routes here.
                    - id: product_route
                      uri: lb://product
                      predicates:
                        - Path=/product/**
                    - id: httpbin_route
                      uri: https://httpbin.org
                      predicates:
                        - Path=/httpbin/**
                      filters:
                        - RewritePath=/httpbin/(?<segment>.*), /$\{segment}

            image.gif

            同时自定义了一些 API 分组:

            private void initCustomizedApis() {
                Set<ApiDefinition> definitions = new HashSet<>();
                ApiDefinition api1 = new ApiDefinition("some_customized_api")
                    .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                        add(new ApiPathPredicateItem().setPattern("/product/baz"));
                        add(new ApiPathPredicateItem().setPattern("/product/foo/**")
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                    }});
                ApiDefinition api2 = new ApiDefinition("another_customized_api")
                    .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                        add(new ApiPathPredicateItem().setPattern("/ahas"));
                    }});
                definitions.add(api1);
                definitions.add(api2);
                GatewayApiDefinitionManager.loadApiDefinitions(definitions);
            }

            image.gif

            那么这里面的 route ID(如 product_route)和 API name(如 some_customized_api)都会被标识为 Sentinel 的资源。比如访问网关的 URL 为 http://localhost:8090/product/foo/22 的时候,对应的统计会加到 product_routesome_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 则不生效。

                Zuul 1.x

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

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

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

                  <dependency>
                      <groupId>com.alibaba.csp</groupId>
                      <artifactId>sentinel-zuul-adapter</artifactId>
                      <version>x.y.z</version>
                  </dependency>

                  image.gif

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

                  @Configuration
                  public class ZuulConfig {
                      @Bean
                      public ZuulFilter sentinelZuulPreFilter() {
                          // We can also provider the filter order in the constructor.
                          return new SentinelZuulPreFilter();
                      }
                      @Bean
                      public ZuulFilter sentinelZuulPostFilter() {
                          return new SentinelZuulPostFilter();
                      }
                      @Bean
                      public ZuulFilter sentinelZuulErrorFilter() {
                          return new SentinelZuulErrorFilter();
                      }
                  }

                  image.gif

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

                  -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)
                  --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)
                  --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)
                  -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)
                  --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)
                  --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)

                  image.gif

                  发生限流之后的处理流程 :

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

                    比如:

                    // 自定义 FallbackProvider 
                    public class MyBlockFallbackProvider implements ZuulBlockFallbackProvider {
                        private Logger logger = LoggerFactory.getLogger(DefaultBlockFallbackProvider.class);
                        // you can define route as service level 
                        @Override
                        public String getRoute() {
                            return "/book/app";
                        }
                        @Override
                            public BlockResponse fallbackResponse(String route, Throwable cause) {
                                RecordLog.info(String.format("[Sentinel DefaultBlockFallbackProvider] Run fallback route: %s", route));
                                if (cause instanceof BlockException) {
                                    return new BlockResponse(429, "Sentinel block exception", route);
                                } else {
                                    return new BlockResponse(500, "System Error", route);
                                }
                            }
                     }
                     // 注册 FallbackProvider
                     ZuulBlockFallbackManager.registerProvider(new MyBlockFallbackProvider());

                    image.gif

                    默认情况下限流后会返回 429 状态码,返回结果为:

                    {
                        "code":429,
                        "message":"Sentinel block exception",
                        "route":"/"
                    }

                    image.gif

                    注意

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

                      网关流控实现原理

                      当通过 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 类型:

                      # 注:通过 Spring Cloud Alibaba Sentinel 自动接入的 API Gateway 整合则无需此参数

                      -Dcsp.sentinel.app.type=1

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

                      image.png

                      网关规则动态配置及网关集群流控可以参考 AHAS Sentinel 网关流控

                      转载自:Sentinel官网



                      文章下方有交流学习区!一起学习进步!也可以前往官网,加入官方微信交流群

                      创作不易,如果觉得文章不错,可以点赞收藏评论

                      你的支持和鼓励是我创作的动力❗❗❗

                      官网Doker 多克官网;官方旗舰店Doker 多克官方旗舰店

                      目录
                      相关文章
                      |
                      5月前
                      |
                      负载均衡 监控 Java
                      Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
                      本文详细介绍了 Spring Cloud Gateway 的核心功能与实践配置。首先讲解了网关模块的创建流程,包括依赖引入(gateway、nacos 服务发现、负载均衡)、端口与服务发现配置,以及路由规则的设置(需注意路径前缀重复与优先级 order)。接着深入解析路由断言,涵盖 After、Before、Path 等 12 种内置断言的参数、作用及配置示例,并说明了自定义断言的实现方法。随后重点阐述过滤器机制,区分路由过滤器(如 AddRequestHeader、RewritePath、RequestRateLimiter 等)与全局过滤器的作用范围与配置方式,提
                      Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
                      |
                      4月前
                      |
                      缓存 JSON NoSQL
                      别再手写过滤器!SpringCloud Gateway 内置30 个,少写 80% 重复代码
                      小富分享Spring Cloud Gateway内置30+过滤器,涵盖请求、响应、路径、安全等场景,无需重复造轮子。通过配置实现Header处理、限流、重试、熔断等功能,提升网关开发效率,避免代码冗余。
                      543 1
                      |
                      7月前
                      |
                      前端开发 Java API
                      Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
                      本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
                      528 0
                      |
                      8月前
                      |
                      缓存 监控 Java
                      说一说 SpringCloud Gateway 堆外内存溢出排查
                      我是小假 期待与你的下一次相遇 ~
                      1133 5
                      |
                      8月前
                      |
                      Java API Nacos
                      |
                      JSON Java API
                      利用Spring Cloud Gateway Predicate优化微服务路由策略
                      Spring Cloud Gateway 的路由配置中,`predicates`​(断言)用于定义哪些请求应该匹配特定的路由规则。 断言是Gateway在进行路由时,根据具体的请求信息如请求路径、请求方法、请求参数等进行匹配的规则。当一个请求的信息符合断言设置的条件时,Gateway就会将该请求路由到对应的服务上。
                      1290 69
                      利用Spring Cloud Gateway Predicate优化微服务路由策略
                      |
                      Java UED Sentinel
                      微服务守护神:Spring Cloud Sentinel,让你的系统在流量洪峰中稳如磐石!
                      【8月更文挑战第29天】Spring Cloud Sentinel结合了阿里巴巴Sentinel的流控、降级、熔断和热点规则等特性,为微服务架构下的应用提供了一套完整的流量控制解决方案。它能够有效应对突发流量,保护服务稳定性,避免雪崩效应,确保系统在高并发下健康运行。通过简单的配置和注解即可实现高效流量控制,适用于高并发场景、依赖服务不稳定及资源保护等多种情况,显著提升系统健壮性和用户体验。
                      343 1
                      |
                      12月前
                      |
                      前端开发 Java Nacos
                      🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
                      本文介绍了如何使用Spring Cloud Alibaba 2023.0.0.0技术栈构建微服务网关,以应对微服务架构中流量治理与安全管控的复杂性。通过一个包含鉴权服务、文件服务和主服务的项目,详细讲解了网关的整合与功能开发。首先,通过统一路由配置,将所有请求集中到网关进行管理;其次,实现了限流防刷功能,防止恶意刷接口;最后,添加了登录鉴权机制,确保用户身份验证。整个过程结合Nacos注册中心,确保服务注册与配置管理的高效性。通过这些实践,帮助开发者更好地理解和应用微服务网关。
                      2126 0
                      🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
                      |
                      JavaScript Java Kotlin
                      深入 Spring Cloud Gateway 过滤器
                      Spring Cloud Gateway 是新一代微服务网关框架,支持多种过滤器实现。本文详解了 `GlobalFilter`、`GatewayFilter` 和 `AbstractGatewayFilterFactory` 三种过滤器的实现方式及其应用场景,帮助开发者高效利用这些工具进行网关开发。
                      1964 1
                      |
                      负载均衡 Java Nacos
                      SpringCloud基础2——Nacos配置、Feign、Gateway
                      nacos配置管理、Feign远程调用、Gateway服务网关
                      SpringCloud基础2——Nacos配置、Feign、Gateway