SpringCloudGateway之限流集成篇

SpringCloudGateway之限流集成篇

在Spring Cloud Gateway中实现限流(Rate Limiting)可以通过集成Spring Cloud Gateway的熔断和限流功能以及第三方限流组件如Sentinel或Resilience4j。

SpringCloudGateway与Sentinel组件集成

添加依赖

首先确保项目包含Spring Cloud Gateway和Sentinel相关依赖。
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <!-- Sentinel Spring Cloud Gateway Adapter -->
    <dependency>
        <groupId>com.alibaba.csp</groupId>
        <artifactId>sentinel-adapter-spring-cloud-gateway-2.x</artifactId>
        <version>{sentinel-version}</version>
    </dependency>
    <!-- Sentinel Core -->
    <dependency>
        <groupId>com.alibaba.csp</groupId>
        <artifactId>sentinel-core</artifactId>
        <version>{sentinel-version}</version>
    </dependency>
</dependencies>

配置Sentinel

在application.yml或application.properties文件中配置Sentinel的相关参数

spring:
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8080 # Sentinel控制台地址
        port: 8719 # Sentinel与控制台之间的通讯端口
      filter:
        url-patterns: "/api/**" # 需要进行限流处理的路由路径

启用Sentinel Gateway适配器

创建一个配置类以启用Sentinel适配器,并注册到Spring容器中

import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.config.SentinelGatewayConfig;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SentinelGatewayConfiguration {

    @Bean
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }

    @Bean
    public SentinelGatewayConfig sentinelGatewayConfig() {
        return new SentinelGatewayConfig();
    }
}

配置限流规则

通过Sentinel控制台或API动态添加限流规则,包括QPS限制、热点限流等策略
为/api/user路由设置QPS限流
为/api/user路由设置QPS限流
在Sentinel控制台上新建一个限流规则,资源名可以是/api/user,然后设置每秒允许的请求次数。

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知青先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值