依赖
<!-- spring data redis reactive 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
网关中加入代码
package com.chenhao.gateway.config;
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 KeyResolverConfiguration {
//key-resolver: "#{@ipKeyResolver}"
@Bean
public KeyResolver ipKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress() + "/" + exchange.getRequest().getRemoteAddress().getHostName());
}
}
网关配置
关注配置点:
redis-rate-limiter.replenishRate: 3 # 令牌桶每秒填充速率
redis-rate-limiter.burstCapacity: 3 # 令牌桶总容量
key-resolver: "#{@ipKeyResolver}" # 使用 SpEL 表达式按名称引用 bean
所有配置点
spring:
redis:
database: 0
host: 192.168.8.51
port: 6379
password:
cloud:
gateway:
discovery:
locator:
lowerCaseServiceId: true
enabled: true
routes:
# 开放接口服务
- id: dcdzsoft-openapi
uri: lb://dcdzsoft-openapi
predicates:
- Path=/openapi/**
filters:
# 签名验签处理
- CacheRequestFilter
- VerifyOpenApiFilter
- StripPrefix=1
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 3 # 令牌桶每秒填充速率
redis-rate-limiter.burstCapacity: 3 # 令牌桶总容量
key-resolver: "#{@ipKeyResolver}" # 使用 SpEL 表达式按名称引用 bean