Spring Cloud Gateway 限流实战,终于有人写清楚了!
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.nio.charset.StandardCharsets;
public class RequestRateLimiterFilter implements GlobalFilter {
private final RequestRateLimiter requestRateLimiter;
public RequestRateLimiterFilter(RequestRateLimiter requestRateLimiter) {
this.requestRateLimiter = requestRateLimiter;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return requestRateLimiter.isAllowed(exchange)
.flatMap(response -> {
if (response.isCommitted()) {
return Mono.error(new RuntimeException("Request rejected"));
}
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
String result = "Requests too many";
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
DataBufferUtils.write(response.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8)), response);
return response.setComplete();
});
}
}
这段代码实现了一个全局过滤器,用于Spring Cloud Gateway中的限流处理。它通过RequestRateLimiter
组件的isAllowed
方法检查请求是否超出了限制,并返回合适的响应。如果请求被拒绝,它将返回一个429 Too Many Requests
响应,并显示一个错误信息。这是一个简洁且有教育意义的实现,对于需要在自己的项目中实现类似功能的开发者来说,值得借鉴。
评论已关闭