1、添加依赖(springboot 2.3.9)可以不加这个依赖
<!--基于Redis实现限流-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
<version>2.2.10.RELEASE</version>
</dependency>
2、创建限流的bean,bean对象放入启动类里
package com.bw2102a;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Mono;
/**
* @author 军哥
* @version 1.0
* @description: ServerShopGatewayApplication
* @date 2023/8/14 11:27
*/
@SpringBootApplication
@Slf4j
public class ServerShopGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ServerShopGatewayApplication.class, args);
}
/**
* @description 通过IP限流
* @author 军哥
* @date 2023/9/5 10:34
* @version 1.0
*/
@Bean(name = "remoteAddrKeyResolver")
public KeyResolver remoteAddrKeyResolver() {
//按请求ip限流
return exchange -> {
log.info("remoteAddrKeyResolver:" + exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
return Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
};
}
/**
* 按IP来限流
*/
// @Bean(name = "ipAddrKeyResolver")
// public KeyResolver ipAddrKeyResolver() {
// // //JDK8的新特性——Lambda表达式
// return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
// }
/**
* 按用户限流
*/
// @Bean(name = "userKeyResolver")
// KeyResolver userKeyResolver() {
// return exchange -> Mono.just(exchange.getRequest().getHeaders().getFirst("token"));
// }
/**
* 按URL限流,即以每秒内请求数按URL分组统计,超出限流的url请求都将返回429状态
*
* @return
*/
// @Bean(name = "apiKeyResolver")
// KeyResolver apiKeyResolver() {
// return exchange -> Mono.just(exchange.getRequest().getPath().toString());
// }
}
3、修改gateway配置文件
# 路由
routes:
- id: server-shop-user #路由id 唯一的
uri: lb://server-shop-user # 请求微服务资源 lb表示负载均衡 deptservice 微服务的名称
predicates: # 断言 路由规则
- Path=/user/**
filters:
- StripPrefix=1
- name: RequestRateLimiter #过滤器名称
args:
key-resolver: "#{@remoteAddrKeyResolver}" #使用SpEL表达式根据#{@beanName}从 Spring 容器中获取 Bean 对象
redis-rate-limiter.replenishRate: 20 # 令牌桶填充的速率 秒为单位
redis-rate-limiter.burstCapacity: 20 # 令牌桶总容量
redis-rate-limiter.requestedTokens: 1 # 每次请求获取的令牌数