分布式限流:Spring Cloud Gateway 限流

分布式限流:Spring Cloud Gateway 限流

在现代微服务架构中,流量控制是一个至关重要的部分。分布式限流作为一种有效的流量控制手段,能够帮助我们保护系统不被突发的流量冲垮。Spring Cloud Gateway支持多种限流方式。

什么是分布式限流

分布式限流是一种在分布式系统中限制请求数量的技术,旨在保护服务不被过载请求压垮。常见的限流算法包括漏桶算法、令牌桶算法和计数器算法。

漏桶算法

漏桶算法通过一个固定容量的漏桶来限制数据的流入和流出,确保流量以恒定速率处理。

令牌桶算法

令牌桶算法在固定时间间隔内向桶中添加一定数量的令牌,请求必须拿到令牌才能被处理,从而控制请求速率。

计数器算法

计数器算法在固定时间窗口内对请求计数,当计数达到预设上限时,拒绝后续请求。

Spring Cloud Gateway 限流实现

Spring Cloud Gateway 提供了多种限流方式,包括基于 Redis 的分布式限流。下面我们将详细介绍如何使用 Redis 实现分布式限流。

配置依赖

首先,在 pom.xml 中添加必要的依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>

配置限流过滤器

application.yml 中配置限流过滤器:

yaml 复制代码
spring:
  cloud:
    gateway:
      routes:
      - id: limit_route
        uri: http://your-service
        filters:
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20

启用 Redis

确保 Redis 服务正在运行,并在 application.yml 中配置 Redis 连接:

yaml 复制代码
spring:
  redis:
    host: localhost
    port: 6379

自定义限流键

为了根据不同的业务需求自定义限流键,可以实现 KeyResolver 接口:

java 复制代码
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

@Configuration
public class RateLimiterConfiguration {

    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }
}

application.yml 中引用自定义的 KeyResolver

yaml 复制代码
spring:
  cloud:
    gateway:
      routes:
      - id: limit_route
        uri: http://your-service
        filters:
        - name: RequestRateLimiter
          args:
            key-resolver: "#{@userKeyResolver}"
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20

参考链接

相关推荐
做个文艺程序员12 小时前
私有 LLM 多机多卡分布式推理:Pipeline Parallel vs Tensor Parallel 踩坑全记录
人工智能·分布式
foundbug99915 小时前
Matlab基于分布式模型预测控制的多固定翼无人机共识控制
分布式·matlab·无人机
一个有温度的技术博主15 小时前
Redis集群实战:如何实现节点的弹性伸缩与数据迁移?
redis·分布式·缓存·架构
小雨青年17 小时前
鸿蒙 HarmonyOS 6 | 分布式数据同步详解
分布式·华为·harmonyos
2501_9333295518 小时前
Infoseek舆情监测系统:基于大模型与多模态AI的品牌公关中台架构设计与实现
人工智能·分布式·自然语言处理·架构
小红的布丁18 小时前
MySQL 和 Redis 数据一致性,以及 Redis 与 ZooKeeper 分布式锁对比
redis·分布式·mysql
qq_3962279518 小时前
Git 分布式版本控制
分布式·git
富士康质检员张全蛋18 小时前
Kafka JMS
分布式·kafka
心勤则明19 小时前
Spring AI Alibaba 分布式智能体实战:基于 A2A 协议的架构演进与落地
人工智能·分布式·spring
weisian15119 小时前
Java并发编程--29-分布式ID的6种方案:从单机到分库分表的“身份证”设计
java·分布式·雪花算法·美团leaf·百度uid