【Java编程系列】Springcloud-gateway自带限流方案实践篇
    		       		warning:
    		            这篇文章距离上次修改已过426天,其中的内容可能已经有所变动。
    		        
        		                
                
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;
 
public class RequestRateLimiterGlobalFilter implements GlobalFilter {
 
    private final RequestRateLimiter requestRateLimiter;
 
    public RequestRateLimiterGlobalFilter(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 body = "Custom response for Too Many Requests";
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    return response.writeWith(Mono.just(response.bufferFactory().wrap(body.getBytes())));
                })
                .onErrorResume(e -> {
                    ServerHttpResponse response = exchange.getResponse();
                    response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
                    String body = "Internal Server Error, please try again later";
                    response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                    return response.writeWith(Mono.just(response.bufferFactory().wrap(body.getBytes())));
                })
                .then(Mono.empty()); // continue filtering other filters
    }
}这个代码示例展示了如何实现一个自定义的全局过滤器,用于Spring Cloud Gateway的请求限流。它使用了RequestRateLimiter服务来决定是否允许请求通过,并提供了一个自定义的响应体,如果请求被拒绝则返回。同时,它还处理了可能发生的错误,并向客户端返回一个内部服务器错误的响应。
评论已关闭