当前位置: 首页 > article >正文

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,然后设置每秒允许的请求次数。


http://www.kler.cn/a/271827.html

相关文章:

  • 代码随想录day23(2)二叉树:从中序与后序遍历序列构造二叉树(leetcode106)
  • 【教学类-34-10】20240313 春天拼图(Midjounery生成线描图,4*4格拼图块)(AI对话大师)
  • 【深度学习模型移植】用torch普通算子组合替代torch.einsum方法
  • 圈子社交系统-多人语音-交友-陪玩-活动报名-商城-二手论坛-源码交付,支持二开!
  • C++ 中的虚函数和多态性
  • docker实战(2)
  • 软考76-上午题-【面向对象技术3-设计模式】-创建型设计模式01
  • Oracle 部署及基础使用
  • Matlab/simulink基于模糊PID智能控制的温度控制系统建模仿真
  • 一起玩儿3D打印机——04 Marlin固件的配置(一)
  • Docker出现容器名称重复如何解决
  • 驾驭Docker镜像海洋:Nexus一站式仓库管理解决方案深度解析及实战指南
  • Hadoop学习3:问题解决
  • 【PyQt错误集 - 1】:PyQt调用多线程导致窗口异常退出的问题分析(进程已结束,退出代码 -1073741819 (0xC0000005))
  • 小蓝的漆房——算法思路
  • Blocks —— 《Objective-C高级编程 iOS与OS X多线程和内存管理》
  • 通过对话式人工智能实现个性化用户体验
  • 论文阅读——GeoChat(cvpr2024)
  • Linux运维相关基础知识
  • 030—pandas 对数据透视并将多层索引整合为一列