Spring cloud gateWay 限流器限流(一)
转载请注明出处:
spring cloud 提供了限流操作的功能,其使用步骤如下:
1.引入maven依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis-reactive</artifactId> </dependency>
2.封装限流过滤器的方法:
import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import reactor.core.publisher.Mono; /** * spring cloud 的限流器配置 * 通过KeyResolver来指定限流的Key,比如我们需要根据用户来做限流,IP来做限流等等。 */ @Configuration public class SpringCloudRateLimiter { /** * 用户限流 * 使用这种方式限流,请求路径中必须携带userId参数。 * @return */ @Bean KeyResolver userKeyResolver() { return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId")); } /** * ip限流 * @return */ @Bean public KeyResolver ipKeyResolver() { return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
// return exchange -> Mono.just(exchange.getRequest().getHeaders().getFirst("X-Forwarded-For"))
}
/** * 接口限流 * 获取请求地址的uri作为限流key * @return */ @Bean KeyResolver apiKeyResolver() { return exchange -> Mono.just(exchange.getRequest().getPath().value()); } }
3.配置config中的yaml过滤配置:
server: port: 8084 spring: redis: host: 127.0.0.1 port: 6379 cloud: gateway: routes: - id: fsh-house uri: lb://fsh-house predicates: - Path=/house/** filters: - name: RequestRateLimiter args: redis-rate-limiter.replenishRate: 10 # 令牌桶每秒填充平均速率
redis-rate-limiter.burstCapacity: 20 # 令牌桶的上限
key-resolver: "#{@ipKeyResolver}" # 使用SpEL表达式从Spring容器中获取Bean对象
- filter名称必须是RequestRateLimiter
- redis-rate-limiter.replenishRate:允许用户每秒处理多少个请求
- redis-rate-limiter.burstCapacity:令牌桶的容量,允许在一秒钟内完成的最大请求数
- key-resolver:使用SpEL按名称引用bean
4. spring cloud gateway
spring cloud gateway 限流使用的 也是通过redis lua 脚本进行交流,其位置如下: