Spring Cloud Gateway 网关限流
Spring Cloud Gateway 限流
一、背景
在我们平时开发过程中,一般一个请求都是需要经过多个微服务的,**比如:**请求从A服务流过B服务,如果A服务请求过快,导致B服务响应慢,那么必然会导致系统出现问题。因为,我们就需要有限流操作。
二、实现功能
提供自定义的限流key生成,需要实现
KeyResolver接口。提供默认的限流算法,实现实现
RateLimiter接口。当限流的key为空时,直接不限流,放行,由参数
spring.cloud.gateway.routes[x].filters[x].args[x].deny-empty-key来控制限流时返回客户端的相应码有
spring.cloud.gateway.routes[x].filters[x].args[x].status-code来控制,需要写这个org.springframework.http.HttpStatus类的枚举值。RequestRateLimiter只能使用name || args这种方式来配置,不能使用简写的方式来配置。

RequestRateLimiter过滤器的redis-rate-limiter参数是在RedisRateLimiter的CONFIGURATION_PROPERTY_NAME属性配置的。构造方法中用到了。
三、网关层限流
限流的key 生成规则,默认是 PrincipalNameKeyResolver来实现
限流算法,默认是 RedisRateLimiter来实现,是令牌桶算法。
1、使用默认的redis来限流
在Spring Cloud Gateway中默认提供了 RequestRateLimiter 过滤器来实现限流操作。
1、引入jar包
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
2、编写配置文件
spring:
application:
name: gateway-9205
cloud:
nacos:
discovery:
server-addr: localhost:8847
gateway:
routes:
- id: user-provider-9206
uri: lb://user-provider-9206
predicates:
- Path=/user/**
filters:
- RewritePath=/user(?<segment>/?.*), $\{segment}
- name: RequestRateLimiter
args:
# 如果返回的key是空的话,则不进行限流
deny-empty-key: false
# 每秒产生多少个令牌
redis-rate-limiter.replenishRate: 1
# 1秒内最大的令牌,即在1s内可以允许的突发流程,设置为0,表示阻止所有的请求
redis-rate-limiter.burstCapacity: 1
# 每次请求申请几个令牌
redis-rate-limiter.requestedTokens: 1
redis:
host: 192.168.7.1
database: 12
port: 6379
password: 123456
server:
port: 9205
debug: true

3、网关正常响应

4、网关限流响应

2、自定义限流算法和限流key
1、自定义限流key
编写一个类实现 KeyResolver 接口即可。
package com.huan.study.gateway;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Optional;
/**
* 限流的key获取
*
* @author huan.fu 2021/9/7 - 上午10:25
*/
@Slf4j
@Component
public class DefaultGatewayKeyResolver implements KeyResolver {
@Override
public Mono<String> resolve(ServerWebExchange exchange) {
// 获取当前路由
Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
ServerHttpRequest request = exchange.getRequest();
String uri = request.getURI().getPath();
log.info("当前返回的uri:[{}]", uri);
return Mono.just(Optional.ofNullable(route).map(Route::getId).orElse("") + "/" + uri);
}
}
配置文件中的写法(部分)
spring:
cloud:
gateway:
routes:
- id: user-provider-9206
filters:
- name: RequestRateLimiter
args:
# 返回限流的key
key-resolver: "#{@defaultGatewayKeyResolver}"
2、自定义限流算法
编写一个类实现 RateLimiter ,此处使用内存限流
package com.huan.study.gateway;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.RateLimiter;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.ratelimit.AbstractRateLimiter;
import org.springframework.cloud.gateway.support.ConfigurationService;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
/**
* @author huan.fu 2021/9/7 - 上午10:36
*/
@Component
@Slf4j
@Primary
public class DefaultGatewayRateLimiter extends AbstractRateLimiter<DefaultGatewayRateLimiter.Config> {
/**
* 和配置文件中的配置属性相对应
*/
private static final String CONFIGURATION_PROPERTY_NAME = "default-gateway-rate-limiter";
private RateLimiter rateLimiter = RateLimiter.create(1);
protected DefaultGatewayRateLimiter(ConfigurationService configurationService) {
super(DefaultGatewayRateLimiter.Config.class, CONFIGURATION_PROPERTY_NAME, configurationService);
}
@Override
public Mono<Response> isAllowed(String routeId, String id) {
log.info("网关默认的限流 routeId:[{}],id:[{}]", routeId, id);
Config config = getConfig().get(routeId);
return Mono.fromSupplier(() -> {
boolean acquire = rateLimiter.tryAcquire(config.requestedTokens);
if (acquire) {
return new Response(true, Maps.newHashMap());
} else {
return new Response(false, Maps.newHashMap());
}
});
}
@Getter
@Setter
@ToString
public static class Config {
/**
* 每次请求多少个 token
*/
private Integer requestedTokens;
}
}
配置文件中的写法(部分)
spring:
cloud:
gateway:
routes:
- id: user-provider-9206
filters:
- name: RequestRateLimiter
args:
# 自定义限流规则
rate-limiter: "#{@defaultGatewayRateLimiter}"
注意️:
这个类需要加上 @Primary 注解。
3、配置文件中的写法
spring:
application:
name: gateway-9205
cloud:
nacos:
discovery:
server-addr: localhost:8847
gateway:
routes:
- id: user-provider-9206
uri: lb://user-provider-9206
predicates:
- Path=/user/**
filters:
- RewritePath=/user(?<segment>/?.*), $\{segment}
- name: RequestRateLimiter
args:
# 自定义限流规则
rate-limiter: "#{@defaultGatewayRateLimiter}"
# 返回限流的key
key-resolver: "#{@defaultGatewayKeyResolver}"
# 如果返回的key是空的话,则不进行限流
deny-empty-key: false
# 限流后向客户端返回的响应码429,请求太多
status-code: TOO_MANY_REQUESTS
# 每次请求申请几个令牌 default-gateway-rate-limiter 的值是在 defaultGatewayRateLimiter 中定义的。
default-gateway-rate-limiter.requestedTokens: 1
server:
port: 9205
debug: true
四、完成代码
https://gitee.com/huan1993/spring-cloud-alibaba-parent/tree/master/gateway-redis-limiter
五、参考文档
1、https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#the-redis-ratelimiter
Spring Cloud Gateway 网关限流的更多相关文章
- 微服务架构spring cloud - gateway网关限流
1.算法 在高并发的应用中,限流是一个绕不开的话题.限流可以保障我们的 API 服务对所有用户的可用性,也可以防止网络攻击. 一般开发高并发系统常见的限流有:限制总并发数(比如数据库连接池.线程池). ...
- spring cloud gateway 之限流篇
转载请标明出处: https://www.fangzhipeng.com 本文出自方志朋的博客 在高并发的系统中,往往需要在系统中做限流,一方面是为了防止大量的请求使服务器过载,导致服务不可用,另一方 ...
- spring boot gateway自定义限流
参考:https://blog.csdn.net/ErickPang/article/details/84680132 采用自带默认网关请参照微服务架构spring cloud - gateway网关 ...
- Spring Cloud gateway 网关服务二 断言、过滤器
微服务当前这么火爆的程度,如果不能学会一种微服务框架技术.怎么能升职加薪,增加简历的筹码?spring cloud 和 Dubbo 需要单独学习.说没有时间?没有精力?要学俩个框架?而Spring C ...
- Spring Cloud gateway 网关四 动态路由
微服务当前这么火爆的程度,如果不能学会一种微服务框架技术.怎么能升职加薪,增加简历的筹码?spring cloud 和 Dubbo 需要单独学习.说没有时间?没有精力?要学俩个框架?而Spring C ...
- Spring Cloud实战 | 第十一篇:Spring Cloud Gateway 网关实现对RESTful接口权限控制和按钮权限控制
一. 前言 hi,大家好,这应该是农历年前的关于开源项目 的最后一篇文章了. 有来商城 是基于 Spring Cloud OAuth2 + Spring Cloud Gateway + JWT实现的统 ...
- .net core下,Ocelot网关与Spring Cloud Gateway网关的对比测试
有感于 myzony 发布的 针对 Ocelot 网关的性能测试 ,并且公司下一步也需要对.net和java的应用做一定的整合,于是对Ocelot网关.Spring Cloud Gateway网关做个 ...
- Spring Cloud gateway 网关服务 一
之前我们介绍了 zuul网关服务,今天聊聊spring cloud gateway 作为spring cloud的亲儿子网关服务.很多的想法都是参照zuul,为了考虑zuul 迁移到gateway 提 ...
- 从0开始构建你的api网关--Spring Cloud Gateway网关实战及原理解析
API 网关 API 网关出现的原因是微服务架构的出现,不同的微服务一般会有不同的网络地址,而外部客户端可能需要调用多个服务的接口才能完成一个业务需求,如果让客户端直接与各个微服务通信,会有以下的问题 ...
随机推荐
- Ubuntu / CoreOS修改DNS配置
不要直接手动修改文件 /etc/resolv.conf 安装好Ubuntu之后设置了静态IP地址,再重启后就无法解析域名.想重新设置一下DNS,打开/etc/resolv.conf cat /etc/ ...
- 【数据库上】第五讲 E-R模型扩展知识
第五讲 E-R模型扩展知识 一.E-R模型设计主意问题 1.1 用实体还是实体集 案例:学院对象的表示 应将各个学院看做实体集,还是实体? 方法一:将各个学院看作一个实体集 如果各学院具有不同属性特征 ...
- 【LeetCode】862. 和至少为 K 的最短子数组
862. 和至少为 K 的最短子数组 知识点:单调:队列:前缀和 题目描述 返回 A 的最短的非空连续子数组的长度,该子数组的和至少为 K . 如果没有和至少为 K 的非空子数组,返回 -1 . 示例 ...
- project read error(项目读取错误)
maven的pom文件出现project read error 1,打开电脑cmd操作界面,在cmd界面找到打开出错项目的文件夹; 比如我的项目文件夹在D:\>eclipse-jee-file\ ...
- 优雅地创建未定义类PHP对象
在PHP中,如果没有事先准备好类,需要创建一个未定义类的对象,我们可以采用下面三种方式: new stdClass() new class{} (object)[] 首先是stdClass,这个类是一 ...
- 根据类拼凑成url参数
/// <summary> /// 根据类拼凑成url参数 /// </summary> /// <typeparam name ...
- JMeter主要元件
配置元件 http cookie管理器 http信息头管理器 http请求默认值 统一管理 快速切换测试环境 http cache管理器 静态资源 监听器元件 查看结果树 分析查看某个请求的详情 请求 ...
- spl_autoload_register 实现自动加载
spl_autoload_register 注册给定的函数作为 __autoload 的实现 bool spl_autoload_register ([ callable $autoload_func ...
- 踩坑系列《二》NewProxyResultSet.isClosed()Z is abstract 报错踩坑
在运行测试类的时候莫名其妙的报了个 NewProxyResultSet.isClosed()Z is abstract 这个错误,之前出现过这个错误,以为是版本出现了问题 就将版本 0.9.1.2 改 ...
- Snipaste屏幕截图的使用
什么是Snipaste Snipaste是一款屏幕截图软件 类似于微信的截图 Snipaste使用步骤 百度搜索Snipaste 如图 点击 根据自己电脑系统选择安装 下载完成后 解压到当前文件夹 点 ...