Spring Cloud Gateway Only One Get RequestBody


本文作为记录 Gateway 组件在使用过程中,Body 仅可获取一次的问题。
感谢 天马行空大佬 https://www.cnblogs.com/JWMA/p/12603248.html

在做验签与接口出入参加密时,当使用POST请求时碰到一个这样的问题:
java.lang.IllegalStateException: Only one connection receive subscriber allowed.​
原因无法从请求中获取两次请求体。

想要去解决他只需要新增一个Filter类即可。
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * Body 缓存过滤器
 * @author cuixiaojian
 */
@Component
public class CacheBodyGlobalFilter implements Ordered, GlobalFilter {
    
    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (exchange.getRequest().getHeaders().getContentType() == null) {
            return chain.filter(exchange);
        } else {
            return DataBufferUtils.join(exchange.getRequest().getBody())
                .flatMap(dataBuffer -> {
                DataBufferUtils.retain(dataBuffer);
                Flux cachedFlux = Flux
                    .defer(() -> Flux.just(dataBuffer.slice(0, dataBuffer.readableByteCount())));
                ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(
                    exchange.getRequest()) {
                    @Override
                    public Flux getBody() {
                    return cachedFlux;
                    }
            };
            
            return chain.filter(exchange.mutate().request(mutatedRequest).build());
            });
        }
    }
    
    /**
    * 将此过滤级别设置为最高
    */
    @Override
    public int getOrder() {
    	return Ordered.HIGHEST_PRECEDENCE;
    }

}
这里是自定义过滤器
@Component
public class JwtFiler implements GlobalFilter, Ordered {
    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		// 自定义验证
		// ......
        return chain.filter(exchange.mutate().build());
    }
    @Override
    public int getOrder() {
        return -90;
    }
}

你可能感兴趣的:(Gateway)