Search in sources :

Example 1 with RateLimiter

use of org.springframework.cloud.gateway.filter.ratelimit.RateLimiter in project spring-cloud-gateway by spring-cloud.

the class RequestRateLimiterGatewayFilterFactory method apply.

@SuppressWarnings("unchecked")
@Override
public GatewayFilter apply(Config config) {
    KeyResolver resolver = (config.keyResolver == null) ? defaultKeyResolver : config.keyResolver;
    RateLimiter<Object> limiter = (config.rateLimiter == null) ? defaultRateLimiter : config.rateLimiter;
    return (exchange, chain) -> {
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        return resolver.resolve(exchange).flatMap(key -> limiter.isAllowed(route.getId(), key).flatMap(response -> {
            if (response.isAllowed()) {
                return chain.filter(exchange);
            }
            exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            return exchange.getResponse().setComplete();
        }));
    };
}
Also used : HttpStatus(org.springframework.http.HttpStatus) ServerWebExchangeUtils(org.springframework.cloud.gateway.support.ServerWebExchangeUtils) RateLimiter(org.springframework.cloud.gateway.filter.ratelimit.RateLimiter) GatewayFilter(org.springframework.cloud.gateway.filter.GatewayFilter) KeyResolver(org.springframework.cloud.gateway.filter.ratelimit.KeyResolver) Route(org.springframework.cloud.gateway.route.Route) KeyResolver(org.springframework.cloud.gateway.filter.ratelimit.KeyResolver) Route(org.springframework.cloud.gateway.route.Route)

Aggregations

GatewayFilter (org.springframework.cloud.gateway.filter.GatewayFilter)1 KeyResolver (org.springframework.cloud.gateway.filter.ratelimit.KeyResolver)1 RateLimiter (org.springframework.cloud.gateway.filter.ratelimit.RateLimiter)1 Route (org.springframework.cloud.gateway.route.Route)1 ServerWebExchangeUtils (org.springframework.cloud.gateway.support.ServerWebExchangeUtils)1 HttpStatus (org.springframework.http.HttpStatus)1