一文速通 spring-cloud-starter-gateway + redis实现限制IP访问次数已达到限流和防恶意刷请求的效果

写在前面,如果项目同时存在spring-cloud-starter-gateway依赖和spring-boot-starter-web依赖,会导致过滤器等配置发送冲突导致项目启动失败。所以使用时候,要把spring-boot-starter-web依赖去掉或者禁用!!!

 一、pom文件导入依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
            <version>3.1.6</version>
        </dependency>


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

二、YML文件

spring:
  main:
    web-application-type: reactive
        #web-application-type: servlet #使用的时候,二选一
  cloud:
     Spring Cloud Gateway 配置项,对应 GatewayProperties 类
    gateway:
      discovery:
        locator:
          enabled: true
      # 路由配置项,对应 RouteDefinition 数组
      routes:
        - id:  rate_limiter # 唯一的路由编号
          uri: localhost:8080/ # 路由到的目标地址
          predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
            - Path=/**
#            - After=2017-01-20T17:42:47.789-07:00[America/Denver]
          filters:
            - name: RequestRateLimiter
              args:
                key-resolver: "#{@ipKeyResolver}" # 获取限流 KEY 的 Bean 的名字
                redis-rate-limiter.replenishRate: 100 # 令牌桶的每秒放的数量
                redis-rate-limiter.burstCapacity: 500 # 令牌桶的最大令牌数

三、配置类

package scau.miniprogram.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @description 限流 KEY 的 Bean ,通过解析请求的来源 IP 作为限流 KEY,这样我们就能实现基于 IP 的请求限流。
 * @ClassName: GatewayConfig
 * @author: zijin
 * @date: 2023/7/21
 * @Copyright:
 */
@Configuration
public class GatewayConfig {

    @Bean
    public KeyResolver ipKeyResolver() {
        return new KeyResolver() {

            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                String host = exchange.getRequest().getRemoteAddress().getHostName();
                System.out.println("!!!!!!!!");
                System.err.println("IP是 "+ host);
                // 获取请求的 IP
                return Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
            }

        };
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值