API网关的默认方法限流是针对每个客户端的。具体的实现方式可以根据不同的API网关的实现框架有所不同。下面是一个使用Spring Cloud Gateway作为API网关的示例代码,展示如何对每个客户端进行限流:
@Configuration
public class GatewayConfiguration {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("example_route", r -> r.path("/example")
.filters(f -> f.requestRateLimiter(
c -> c.setKeyResolver(ipKeyResolver())
.setRateLimiter(redisRateLimiter())))
.uri("http://example-service") // 将请求转发到实际的服务
)
.build();
}
@Bean
public KeyResolver ipKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
}
@Bean
public RedisRateLimiter redisRateLimiter() {
return new RedisRateLimiter(10, 20); // 每秒允许10个请求, 桶容量为20
}
}
在上述示例中,我们定义了一个自定义的路由定位器,使用requestRateLimiter
过滤器来实现限流。通过ipKeyResolver
方法,我们将每个请求的IP地址作为限流的唯一键。通过redisRateLimiter
方法,我们创建一个RedisRateLimiter对象,设置每秒允许的请求数和桶容量。
需要注意的是,上述示例使用了Redis作为限流的存储,你可以根据自己的需求选择其他的存储方式,如基于内存的限流器或者其他数据库。