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 脚本进行交流,其位置如下:
标签:
spring cloud
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
2017-12-08 org.apache.jasper.JasperException: /WEB-INF/view/../../../common/common1.jsp (line: 7, column: 1) Page directive must not have multiple occurrences of pageencoding
2017-12-08 Uncaught TypeError: $(...).daterangepicker is not a function