如何解决java.lang.IllegalStateException:只允许一个连接接收订阅者

时间:2018-09-28 10:15:17

标签: spring-cloud spring-webflux subscriber spring-cloud-gateway

我使用spring-cloud-gateway构建网关服务,但是当该服务接收POST请求时,会发生以下异常:“ java.lang.IllegalStateException:仅一个连接接收到允许的订阅者”。如何解决呢?下面是我的代码。谢谢。

@Override
public GatewayFilter apply(Object config) {
    return ((exchange, chain) -> {
        URI uri = exchange.getRequest().getURI();
        URI ex = UriComponentsBuilder.fromUri(uri).build(true).toUri();
        ServerHttpRequest request = exchange.getRequest().mutate().uri(ex).build();
        if ("POST".equalsIgnoreCase(request.getMethodValue())) {
            Flux<DataBuffer> body = request.getBody();
            AtomicReference<String> bodyRef = new AtomicReference<>(); //used for cache request body

            //Cache request
            body.subscribe(dataBuffer -> {
                CharBuffer charBuffer = StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer());
                DataBufferUtils.release(dataBuffer);
                bodyRef.set(charBuffer.toString());
            });

            //generate bodyFlux
            String bodyStr = bodyRef.get();
            System.out.println(bodyStr);
            DataBuffer bodyDataBuffer = stringBuffer(bodyStr);
            Flux<DataBuffer> bodyFlux = Flux.just(bodyDataBuffer);

            // generate request by bodyFlux
            request = new ServerHttpRequestDecorator(request) {
                @Override
                public Flux<DataBuffer> getBody() {
                    return bodyFlux;
                }
            };
        }
        return chain.filter(exchange.mutate().request(request).build());
    });
}

// Generated DataBuffer from String
protected DataBuffer stringBuffer(String value) {
    byte[] bytes = value.getBytes(StandardCharsets.UTF_8);

    NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
    DataBuffer buffer = nettyDataBufferFactory.allocateBuffer(bytes.length);
    buffer.write(bytes);
    return buffer;
}

1 个答案:

答案 0 :(得分:0)

这看起来像以下问题:https://github.com/spring-cloud/spring-cloud-gateway/issues/541

作为临时的解决方法,您可以在应用程序中定义此bean:

@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
    return new HiddenHttpMethodFilter() {
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
            return chain.filter(exchange);
        }
    };
}

此问题在“格林尼治M1”上已得到修复。