Sentinel 整合 Gateway实现网关流控控制台及规则配置

Sentinel 整合 Spring Cloud Gateway 实现网关层面的流量控制,主要步骤如下:

  1. 添加依赖
    在 Gateway 项目的 pom.xml 文件中添加 Sentinel 的 Gateway 适配器依赖。
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel-gateway</artifactId>
</dependency>
  1. 配置启动类
    在 Gateway 应用的启动类上添加 @EnableSentinelGateway 注解启用 Sentinel 网关流控。
import com.alibaba.cloud.sentinel.gateway.SentinelGatewayAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapper;

@SpringBootApplication
@EnableDiscoveryClient
@EnableSentinelGateway // 启用 Sentinel 网关流控
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

    // 可以定义自定义路由映射规则等其他配置
}
  1. 配置 Sentinel 控制台
    需要在 Sentinel 控制台上配置网关流控规则。在 Sentinel 控制台 -> 流控规则 -> 新增网关流控规则页面,你可以根据 API 路径、请求方法、参数等多个维度设置限流规则。

  2. YAML 配置文件(可选)
    如果需要通过配置文件来配置 Sentinel 相关属性,可以在 application.yml 或 application.properties 中进行配置,例如:

spring:
  cloud:
    gateway:
      routes:
        - id: sentinel_route
          uri: lb://service-provider
          predicates:
            - Path=/provider/**
          filters:
            - name: SentinelGatewayFilter # 添加 Sentinel 网关过滤器
              args:
               资源名称: /provider/**
                阈值类型: QPS
                阈值: 10
                关联响应码: 429

sentinel:
  transport:
    dashboard: localhost:8080 # Sentinel 控制台地址
    port: 8719 # 客户端与 Sentinel 控制台通信端口

这样,Sentinel 就可以对 Spring Cloud Gateway 中的请求进行流量控制了。在 Sentinel 控制台上配置的规则会实时生效,实现动态的流量控制管理。

  • 14
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值