点击左上角蓝字,关注“锅外的大佬”

专注分享国外最新技术内容

学习本篇文章之前如果你还没有了解过Sentinel是什么的话,请先学习一下分布式系统的流量防卫兵Sentinel-入门指南。这样就能轻松学习Spring Cloud Alibaba Sentinel的使用。

1.简介

Sentinel 支持对 Spring Cloud GatewayZuul 等主流的 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 和 matchStrategy:为后续参数匹配特性预留,目前未实现。

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

2.网关流控实现原理

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

在这里插入图片描述

3.Spring Cloud Gateway 的支持

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

  • route 维度:即在 Spring 配置文件中配置的路由条目,资源名为对应的routeId

  • 自定义 API 维度:用户可以利用 Sentinel 提供的 API 来自定义一些 API 分组

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

  1. <dependency>

  2. <groupId>org.springframework.boot</groupId>

  3. <artifactId>spring-boot-starter-actuator</artifactId>

  4. </dependency>

  5. <dependency>

  6. <groupId>org.springframework.boot</groupId>

  7. <artifactId>spring-boot-starter-webflux</artifactId>

  8. </dependency>

  9. <dependency>

  10. <groupId>org.springframework.boot</groupId>

  11. <artifactId>spring-boot-starter-actuator</artifactId>

  12. </dependency>

  13. <dependency>

  14. <groupId>org.springframework.cloud</groupId>

  15. <artifactId>spring-cloud-starter-gateway</artifactId>

  16. </dependency>

  17. <dependency>

  18. <groupId>com.alibaba.cloud</groupId>

  19. <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>

  20. <version>2.1.0.RELEASE</version>

  21. </dependency>

3.2 添加SentinelGatewayFilter和SentinelGatewayBlockExceptionHandler实例

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

  1. @Configuration

  2. public class GatewayConfiguration {

  3. private final List<ViewResolver> viewResolvers;

  4. private final ServerCodecConfigurer serverCodecConfigurer;

  5. public GatewayConfiguration(ObjectProvider<List<ViewResolver>> 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. }

3.3 添加application.yml配置

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

  1. server:

  2. port: 9022

  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>.*), /$\{segment}

3.4 添加 API 分组和route 维度

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

  1. private void initCustomizedApis() {

  2. Set<ApiDefinition> definitions = new HashSet<>();

  3. ApiDefinition api1 = new ApiDefinition("some_customized_api")

  4. .setPredicateItems(new HashSet<ApiPredicateItem>() {{

  5. add(new ApiPathPredicateItem().setPattern("/ahas"));

  6. add(new ApiPathPredicateItem().setPattern("/product/**")

  7. .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));

  8. }});

  9. ApiDefinition api2 = new ApiDefinition("another_customized_api")

  10. .setPredicateItems(new HashSet<ApiPredicateItem>() {{

  11. add(new ApiPathPredicateItem().setPattern("/**")

  12. .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));

  13. }});

  14. definitions.add(api1);

  15. definitions.add(api2);

  16. GatewayApiDefinitionManager.loadApiDefinitions(definitions);

  17. }

同时也定义一些route纬度:

  1. private void initGatewayRules() {

  2. Set<GatewayFlowRule> rules = new HashSet<>();

  3. rules.add(new GatewayFlowRule("aliyun_route")

  4. .setCount(10)

  5. .setIntervalSec(1)

  6. );

  7. rules.add(new GatewayFlowRule("aliyun_route")

  8. .setCount(2)

  9. .setIntervalSec(2)

  10. .setBurst(2)

  11. .setParamItem(new GatewayParamFlowItem()

  12. .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)

  13. )

  14. );

  15. rules.add(new GatewayFlowRule("httpbin_route")

  16. .setCount(10)

  17. .setIntervalSec(1)

  18. .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER)

  19. .setMaxQueueingTimeoutMs(600)

  20. .setParamItem(new GatewayParamFlowItem()

  21. .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)

  22. .setFieldName("X-Sentinel-Flag")

  23. )

  24. );

  25. rules.add(new GatewayFlowRule("httpbin_route")

  26. .setCount(1)

  27. .setIntervalSec(1)

  28. .setParamItem(new GatewayParamFlowItem()

  29. .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)

  30. .setFieldName("pa")

  31. )

  32. );

  33. rules.add(new GatewayFlowRule("httpbin_route")

  34. .setCount(2)

  35. .setIntervalSec(30)

  36. .setParamItem(new GatewayParamFlowItem()

  37. .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)

  38. .setFieldName("type")

  39. .setPattern("warn")

  40. .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS)

  41. )

  42. );

  43. rules.add(new GatewayFlowRule("some_customized_api")

  44. .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)

  45. .setCount(5)

  46. .setIntervalSec(1)

  47. .setParamItem(new GatewayParamFlowItem()

  48. .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM)

  49. .setFieldName("pn")

  50. )

  51. );

  52. /**

  53. * 手动加载网关规则

  54. */

  55. GatewayRuleManager.loadRules(rules);

  56. }

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

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

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

3.5 添加服务的启动类

  1. package com.lidong.gateway;

  2. import org.springframework.boot.SpringApplication;

  3. import org.springframework.boot.autoconfigure.SpringBootApplication;

  4. /**

  5. * 开启服务发现

  6. */

  7. @SpringBootApplication

  8. public class SentinelGatewayApplication {

  9. public static void main(String[] args) {

  10. SpringApplication.run(SentinelGatewayApplication.class, args);

  11. }

  12. }

3.6 添加控制台

  1. <dependency>

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

  3. <artifactId>sentinel-transport-simple-http</artifactId>

  4. <version>1.6.3</version>

  5. </dependency>

添加启动参数

-Dcsp.sentinel.app.type=1 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=gateway-sentinel

csp.sentinel.app.type=1  代表网关类型

3.7启动网关服务

java -jar gateway-sentinel.jar  -Dcsp.sentinel.app.type=1 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=gateway-sentinel

然后通过网关访问

http://localhost:9022/product/ahas

我们就可以看到如下的界面,转发到阿里云的ahas的产品页面

3.8 控制台查看

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

我们可以在控制台配置自定义的 API 分组,将一些 URL 匹配模式归为一个 API 分组:lidong然后我们可以在控制台针对预设的 route ID 或自定义的 API 分组配置网关流控规则

到这里一个简单spring-cloud-alibaba-sentinel-gateway网关的案例基本上就完成了。

资料领取,关注公众号

发送福利代码:004,领取八月译文集锦哦~

往期福利:回复 001,002,003

Sentinel 网关流量控制之Spring Cloud Gateway实战相关推荐

  1. Spring Cloud Gateway实战之三:动态路由

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 本文是<Spring Cloud Ga ...

  2. 网关 翻译版本 spring cloud gateway

    Spring Cloud Gateway 官网原文地址 https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html ...

  3. 微服务 API 网关架构演进 Spring Cloud Gateway ShenYu APISIX

    目录 后台服务网关 Spring Cloud Gateway 遇到问题 Apache ShenYu Higress fizz-gateway-community 企业案例 前台流量网关 APISIX ...

  4. 网关 Spring Cloud Gateway 实战负载均衡(Spring Cloud Loadbalancer)

  5. 基于Nacos配置中心实现Spring Cloud Gateway的动态路由管理

    前面我们了解过了Sentinel 网关流量控制之Spring Cloud Gateway实战,今天带给大家是基于Nacos配置中心实现Spring Cloud Gateway的动态路由管理. 1.为什 ...

  6. Spring Cloud Alibaba 实战 | 第十二篇: 微服务整合Sentinel的流控、熔断降级,赋能拥有降级功能的Feign新技能熔断,实现熔断降级双剑合璧(JMeter模拟测试)

    文章目录 一. Sentinel概念 1. 什么是Sentinel? 2. Sentinel功能特性 3. Sentinel VS Hystrix 二. Docker部署Sentinel Dashbo ...

  7. 微服务网关Zuul迁移到Spring Cloud Gateway

    https://juejin.im/post/5ba8daa56fb9a05cfe486ebf 背景 在之前的文章中,我们介绍过微服务网关Spring Cloud Netflix Zuul,前段时间有 ...

  8. ws配置 zuul_微服务网关 Spring Cloud Gateway

    1.  为什么是Spring Cloud Gateway 一句话,Spring Cloud已经放弃Netflix Zuul了.现在Spring Cloud中引用的还是Zuul 1.x版本,而这个版本是 ...

  9. Spring Cloud Gateway(一)为什么用网关、能做什么、为什么选择Gateway、谓词工厂、过滤器配置

    1.为什么用网关?能做什么?为什么选择Gateway? 1.1.为什么用网关 网关api:封装了系统内部架构,为每个客户端提供一个定制的 API.在微服务架构中,服务网关的核心要点是,所有的客户端和消 ...

  10. Spring Cloud(10)——新一代网关Spring Cloud Gateway

    文章目录 Spring Cloud(10)--新一代网关Spring Cloud Gateway 1.背景知识--API网关 2.Spring Cloud Gateway 详细概述 3.Spring ...

最新文章

  1. 一篇价值百万的文章:我为什么在22岁辞去年薪150万的工作?
  2. linux使用线程实现生产者消费者问题,Linux平台下线程同步,实现“生产者消费者问题”...
  3. python绘制3维图-1、2、3维图见过,用Python画出来的六维图见过么?
  4. 本质矩阵svd分解_SVD推荐系统
  5. 计算机与材料化学应用背景介绍,计算机在材料工程中的应用.ppt
  6. 网站被黑的原因真实案例
  7. 构建Spring Boot程序有用的文章
  8. IOC操作Bean管理XML方式(xml自动装配)
  9. xp 优化   转自天涯
  10. eclipse--基本配置
  11. 移动网络设备睁开均盘绕Linux睁开
  12. 程序员:我们都在为错误买单!
  13. linux 脚本 列表,shell -脚本 给出多个数据列表 执行任务
  14. rabbitmq 一个生产者多个消费者_RabbitMQ入门学习系列(二),单生产者消费者
  15. 软件项目管理的重点知识
  16. android wifi热点 信道,wifi 热点配置最优信道(示例代码)
  17. 随机抖音接口php,【php】下载抖音无水印视频接口
  18. 【UE4】如何获取/下载虚幻4(Unreal Engine4)源码
  19. Android开发使用百度地图定位误差过大
  20. AWS EFS vs EBS vs S3(差异和何时使用?)

热门文章

  1. Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)
  2. SpringData ES中一些底层原理的分析
  3. cmd创建一个用户并升级成管理员
  4. 如何隐藏UITabBar 已经如何使已经隐藏的TabBar重现(原创)
  5. Linux音频驱动-AOSC之Platform
  6. 单独编译一个内核模块的方法
  7. 闲谈IPv6-v4/v6协议转换报文的checksum无关性
  8. VPP:Bihash简介
  9. Linux 火焰图(on-cpu , off-cpu , memory)
  10. VS2013 MFC 中DLL链接库断点不能命中的解决方案总结