0
点赞
收藏
分享

微信扫一扫

Spring Cloud Gateway 完整示例:基于redis实现请求限流


本文我将提供一个 完整可运行的 Spring Cloud Gateway 入门示例,包括:

  • 网关服务gateway-service
  • 后端服务backend-service
  • 基于 Redis 的请求限流

1. 工程结构

spring-cloud-gateway-demo
 ├── backend-service     # 模拟微服务
 └── gateway-service     # 网关服务(含限流)

2. backend-service

pom.xml

<dependencies>
    <!-- Spring Boot Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

application.yml

server:
  port: 8081
spring:
  application:
    name: backend-service

控制器

package com.example.backend;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/api/hello")
    public String hello() {
        return "Hello from backend service!";
    }
}

启动后,访问:

http://localhost:8081/api/hello

3. gateway-service

pom.xml

<dependencies>
    <!-- Spring Cloud Gateway -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

    <!-- Redis 依赖(限流需要) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
    </dependency>

    <!-- Actuator 可选 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>2022.0.5</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

application.yml

server:
  port: 9000
spring:
  application:
    name: gateway-service

  cloud:
    gateway:
      routes:
        - id: backend-service
          uri: http://localhost:8081
          predicates:
            - Path=/test/**
          filters:
            - StripPrefix=1
            # 添加限流过滤器
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 2   # 每秒生成令牌数
                redis-rate-limiter.burstCapacity: 5   # 桶容量
                key-resolver: "#{@ipKeyResolver}"     # 使用IP限流

限流 KeyResolver

package com.example.gateway.config;

import org.springframework.cloud.gateway.support.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

@Configuration
public class RateLimiterConfig {

    /**
     * 按 IP 地址限流
     */
    @Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(
                exchange.getRequest()
                        .getRemoteAddress()
                        .getAddress()
                        .getHostAddress()
        );
    }
}

4. 启动步骤

  1. 确保本地 Redis 已启动(默认 localhost:6379)。
  2. 启动 backend-service(端口 8081)。
  3. 启动 gateway-service(端口 9000)。
  4. 访问:

http://localhost:9000/test/api/hello

  • 如果请求速率低:返回

Hello from backend service!

  • 如果请求过快:返回 HTTP 429 Too Many Requests


举报

相关推荐

0 条评论