网关限流方案

网关限流是保护后端服务的一种常见方法,它可以防止流量激增导致系统崩溃。以下是几种常见的网关限流方案及其实现示例:

一、基于Nginx的限流

1. 配置示例(nginx)

复制代码
http {
    # 定义限速器
    limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;

    server {
        location / {
            # 应用限速器
            limit_req zone=mylimit burst=5 nodelay;
            proxy_pass http://backend_service;
        }
    }
}
复制代码

2. 说明

  • limit_req_zone:定义一个限速器,基于客户端IP地址,存储在10m大小的共享内存中,限速为每秒1个请求。
  • limit_req:应用限速规则,允许突发流量5个请求,nodelay表示请求超过突发限制时立即返回错误。

二、基于Spring Cloud Gateway的限流

1. 配置示例(yaml)

复制代码
spring:
  cloud:
    gateway:
      routes:
      - id: limit_route
        uri: http://localhost:8080
        predicates:
        - Path=/api/**
        filters:
        - name: RequestRateLimiter
          args:
            key-resolver: '#{@remoteAddrKeyResolver}'
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20
复制代码

2. 实现Key Resolver(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 RateLimiterConfig {

    @Bean
    public KeyResolver remoteAddrKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
    }
}
复制代码

3. 说明

  • RequestRateLimiter:使用Redis限流器。
  • key-resolver:定义限流键,这里基于客户端IP地址。
  • redis-rate-limiter.replenishRate:每秒新增令牌数。
  • redis-rate-limiter.burstCapacity:令牌桶的最大容量,允许突发流量。

三、基于Kong的限流

1. 配置Kong(shell)

curl -i -X POST http://localhost:8001/services/your_service_name/plugins \
    --data "name=rate-limiting" \
    --data "config.minute=100"

2. 说明

  • config.minute:每分钟允许的最大请求数。

四、基于Envoy的限流

1. 配置示例(yaml)

复制代码
static_resources:
  listeners:
    - name: listener_0
      address:
        socket_address:
          address: 0.0.0.0
          port_value: 10000
      filter_chains:
        - filters:
            - name: envoy.filters.network.http_connection_manager
              config:
                route_config:
                  virtual_hosts:
                    - name: backend
                      domains: ["*"]
                      routes:
                        - match:
                            prefix: "/"
                          route:
                            cluster: service_backend
                http_filters:
                  - name: envoy.filters.http.router
                  - name: envoy.filters.http.local_ratelimit
                    typed_config:
                      "@type": type.googleapis.com/envoy.config.filter.http.local_rate_limit.v2.LocalRateLimit
                      stat_prefix: http_local_rate_limiter
                      token_bucket:
                        max_tokens: 100
                        tokens_per_fill: 10
                        fill_interval: 1s
复制代码

2. 说明

  • token_bucket.max_tokens:令牌桶的最大容量。
  • tokens_per_fill:每次填充的令牌数。
  • fill_interval:填充令牌的时间间隔。

 

实际应用

在实际项目中,根据业务需求和技术栈选择合适的限流方案。例如:

  • Nginx限流:适用于简单、高性能的限流需求。
  • Spring Cloud Gateway限流:适用于Spring生态圈,支持复杂的限流和路由策略。
  • Kong限流:高度可扩展、支持多种插件,适用于大型分布式系统。
  • Envoy限流:提供丰富的流量管理功能,适用于微服务架构。

示例代码

基于Spring Cloud Gateway的示例

pom.xml文件:

复制代码
<dependencies>
    <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>
</dependencies>
复制代码

application.yml文件:

复制代码
spring:
  cloud:
    gateway:
      routes:
      - id: limit_route
        uri: http://localhost:8080
        predicates:
        - Path=/api/**
        filters:
        - name: RequestRateLimiter
          args:
            key-resolver: '#{@remoteAddrKeyResolver}'
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20
复制代码

RateLimiterConfig.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 RateLimiterConfig {

    @Bean
    public KeyResolver remoteAddrKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
    }
}
复制代码

通过上述配置和代码,即可实现基于Spring Cloud Gateway的限流机制。根据实际需求,还可以进一步增加自定义限流策略和监控报警等功能。

 

posted @   zhangleinewcharm  阅读(580)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示