java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Sentinel对Spring Cloud Gateway进行精准限流

Sentinel如何对Spring Cloud Gateway进行精准限流

作者:渔阳镇节度使

还在为微服务网关流量控制发愁?本文手把手教你用Sentinel对Spring Cloud Gateway进行限流,从GatewayFlowRule规则配置到API分组精准匹配,涵盖参数限流、动态规则推送和控制台监控,助你轻松应对高并发场景

在微服务系统中,网关提供了微服务系统的统一入口,所以我们在做限流的时候,肯定是要在网关层面做一个流量的控制,Sentinel 支持对 Spring Cloud Gateway、Zuul 等主流的 API Gateway 进行限流。

网关

Sentinel 1.6.0 引入了 Sentinel API Gateway Adapter Common 模块,此模块中包含网关限流的规则和自定义 API 的实体和管理逻辑:

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

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

网关流控控制台

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

使用方式

首先在网关中添加依赖:

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

网关服务的配置

server:
  port: 9999
spring:
  application:
    name: cloud-gateway-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        # 配置Sentinel dashboard地址
        dashboard: localhost:8080
        # 默认8719端口,键入被占用会自动从8719+1,直到找到未被占用的端口
        port: 8719
    gateway:
      discovery:
        locator:
          enabled: true
        #enabled: true #开启注册中心路由功能
      routes:  # 路由
        - id: nacos-provider #路由ID,没有固定要求,但是要保证唯一,建议配合服务名
          uri: lb://nacos-provider # 匹配提供服务的路由地址
          predicates: # 断言
            - Path=/gate/** # 断言,路径相匹配进行路由

然后在Sentinel控制台中增加Route ID对应的流控 

route ID模式

执行结果

API分组

这是最简单的一种测试方式,在正常生产环境中,可以只会针对某个接口来进行限流,所以还可以配置对应的API分组

精准:精准匹配对应的请求地址

前缀:匹配对应的地址前缀(针对有参数的请求)

正则:通过正则的方式匹配

生产环境中可能还会出现这种路径:

gate/login/aaa
gate/login/v1/aaa
/gate/login/** 这种方式都可以匹配所以需要用到正则

所以想要解决这种问题,其实我们可以把详细的也就是gate/login/v1/aaa这种地址用前缀来匹配,那么对应的这种gate/login/aaa路径就可以直接使用正则来进行匹配,比如:

/gate/login/([a-z]+)

具体演示:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文