我使用 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;
}
这看起来像以下问题: 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"开始修复的。