Spring Gateway基于redis限流

引入redis reactive依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifatId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>

resolver配置:

@Configuration
public class RequestRateLimiterConfig {

    @Bean(name = "remoteAddrKeyResolver")
    public KeyResolver remoteAddrKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
    }

    @Primary
    @Bean(name = "apiKeyResolver")
    public KeyResolver apiKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().value());
    }

}

yaml配置:

server:
  port: 8888

spring:
  cloud:
    gateway:
      routes:
        - id: limit-route
          uri: http://localhost:8080
#         重要:order越小越早捕获,比如filter设置1,Ratelimit设置0,则限流发生在filter前
          order: -40
          predicates:
            - Path=/test/**
          filters:
#             若Path配置如上,访问网关localhost:8888/test/hello,则跳转localhost:8080/hello
            - StripPrefix=1
#             name不可随意更改,factory中已定义
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 1
                redis-rate-limiter.burstCapacity: 1
                key-resolver: '#{@apiKeyResolver}'

重要:如果filter中配置了order,则限流必须要配置order且数值比filter小,否则限流不生效!

上面贴出的是完整的Spring Cloud Gateway的配置,主要配置为filters下的RequestRateLimiterkey-resolver表示使用名为apiKeyResolver的限流配置配置类,此限流方式采用的是令牌桶算法的限流方式

  • redis-rate-limiter.replenishRate:令牌桶每秒填充平均速率
  • redis-rate-limiter.burstCapacity: 令牌桶的总容量

redis中限流key:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值