Sentinel 是面向分布式服务架构的流量控制组件;可适配spring cloud gateway ,实现分布式服务架构 路由流量控制和熔断降级等功能,保障微服务的稳定性。

而sentinel 限流规则可配置在nacos 服务配置中心,通过 推模式 实现sentinel 限流规则的动态修改和实时加载。 

网关限流是针对API Gateway 的场景定制的限流规则,可以针对不同 route 或自定义的 API 分组进行限流,支持针对请求中的参数、Header、来源 IP 等进行定制化的限流。

其中网关限流规则 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 版本开始支持)

Sentinel 适配 Spring Cloud Gateway 网管限流,并通过配置中心 nacos 动态控制限流规则使用步骤:

1.系统目录:

说明,项目以实现gaiway 路由和nacos 服务发现等功能;(具体实现可参照文档 《spring cloud 阶段学习总结(一)》和《spring cloud 阶段学习总结(二)》) 

2.依赖导入

修改 clou-gateway pom 文件,新增依赖 spring-cloud-starter-alibaba-sentinel、spring-cloud-alibaba-sentinel-gateway 和 sentinel-datasource-nacos

完整的pom 文件依赖信息:

<dependencies>
    <!--        spring cloud  gateway -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

    <!--        spring ali cloud nacos 服务发现-->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>

    <!--      spring cloud ali  配置重新  -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>

    <!--        spring boot actuator 监控-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>


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

    <!--        Spring cloud sentinel 网关适配-->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
    </dependency>

    <!--       sentinel nacos 数据源-->
    <dependency>
        <groupId>com.alibaba.csp</groupId>
        <artifactId>sentinel-datasource-nacos</artifactId>
    </dependency>


    <!--        热部署-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
</dependencies>

3.nacos 配置中心 新增网关限流配置规则文件 clou-sentinel-gateway ,新增控制规则;

 注意:

  1. 配置格式 为 json 
  2. resource 为路由id ,与spring gateway 路由配置中的id 相对应。
  3. count 限流阈值

4.修改 clou-gateway 配置文件  bootstrap.yml 文件 新增 sentinel 配置部分

 文件内容: 

server:
  port: 29080

spring:
  application:
    name: spri-clou-gateway
  profiles:
    active: dev

  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
        namespace: db59eae3-ddba-4c8e-9c71-1b709aff5efe

      config:
        server-addr: 127.0.0.1:8848
        namespace: db59eae3-ddba-4c8e-9c71-1b709aff5efe
        group: DEFAULT_GROUP
        name: ${spring.application.name}
        file-extension: yaml
        shared-configs:
          - data-id: application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
            group: DEFAULT_GROUP
            refresh: true # 是否自动刷新配置,默认为 false


    sentinel:
      eager: true #取消控制台懒加载
      datasource:
        ds1:
          nacos:
            server-addr: 127.0.0.1:8848
            dataId: clou-sentinel-gateway
            namespace: db59eae3-ddba-4c8e-9c71-1b709aff5efe
            groupId: DEFAULT_GROUP
            data-type: json
            rule-type: flow

注意:sentinel 配置文件中的  dataId  为 nacos 配置中心 新增网关限流配置规则文件 clou-sentinel-gateway

5.clou-gateway 项目新增配置类 GatewayConfig

 GatewayConfig 配置类文件内容: 

/**
 * Spring Cloud Gateway 网关 流量监控
 *  使用时只需注入对应的 SentinelGatewayFilter 实例以及 SentinelGatewayBlockExceptionHandler 实例即可
 */
@Configuration
public class GatewayConfig {

    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public GatewayConfig(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);
    }

}

6.启动clou-gateway 和 clou-auth 项目,访问 http://localhost:29080/auth/moduleName ,当同一时间访问超过阈值 5 时,界面出现sentinel 限流提示: Blocked by Sentinel: FlowException

 异常提示界面:

 正常访问界面: 

转自链接 :https://www.cnblogs.com/LittlePaper/p/14322417.html

GitHub 加速计划 / sentine / Sentinel
43
7
下载
alibaba/Sentinel: Sentinel 是阿里巴巴开源的一款面向分布式服务架构的流量控制、熔断降级组件,提供实时监控、限流、降级和系统保护功能,适用于微服务治理场景。
最近提交(Master分支:2 个月前 )
a08dc695 * Fix the bugs mentioned in issue #3562 and #3563. Fix the issue in the spring-webmvc-v6x-adapter where, after configuring http-method-specify:true, the prefixes for different request methods were not concatenated. Fix incorrect time unit in the tooltip when adding a new circuit breaker rule with statistical window duration. * Fix the bugs mentioned in issue #3562 and #3563. Fix the issue in the spring-webmvc-v6x-adapter where, after configuring http-method-specify:true, the prefixes for different request methods were not concatenated. Fix incorrect time unit in the tooltip when adding a new circuit breaker rule with statistical window duration. * Fixed the issue where the original test class was affected by the concatenation of resource names after adding the logic for the HTTP prefix concatenation. * remove mseHttpMethodSpecify field and update the unit test as suggested. * retrigger CI 28 天前
e60f0d0e * Simple rules should have higher priority than regular expression rules * Add optional switch to skip regex matching when simple rules already match, default: false, keeps backward compatibility. * fix RuleManagerTest unit test failure 28 天前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐