[spring cloud] [error] java.lang.IllegalStateException: Only one connection receive subscriber allowed.
前言
最近在开发api-gateway的时候遇到了一个问题,网上能够找到的解决方案也很少,之后由公司的大佬解决了这个问题。写下这篇文章记录一下解决方案。希望可以帮助到更多的人。
环境
- java版本:8
- 框架:spring-cloud 2.0.0.RC1
介绍
api-gateway主要接收前端请求,然后对请求的数据进行验证,验证之后请求反向代理到服务器。当请求 method 为 GET 时,可以顺利通过api-gateway。当请求 method 为 POST 时,api-gateway则会报如下错误:
2018-07-18 11:49:04.073 ERROR 3025 --- [ctor-http-nio-4] .a.w.r.e.DefaultErrorWebExceptionHandler : Failed to handle request [POST http://localhost:9000/api/hello] java.lang.IllegalStateException: Only one connection receive subscriber allowed.
at reactor.ipc.netty.channel.FluxReceive.startReceiver(FluxReceive.java:276) ~[reactor-netty-0.7.5.RELEASE.jar:0.7.5.RELEASE]
at reactor.ipc.netty.channel.FluxReceive.lambda$subscribe$2(FluxReceive.java:127) ~[reactor-netty-0.7.5.RELEASE.jar:0.7.5.RELEASE]
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:163) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:404) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:463) ~[netty-transport-4.1.22.Final.jar:4.1.22.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:886) ~[netty-common-4.1.22.Final.jar:4.1.22.Final]
at java.lang.Thread.run(Thread.java:748) ~[na:1.8.0_171]
错误分析
实际上spring-cloud-gateway反向代理的原理是,首先读取原请求的数据,然后构造一个新的请求,将原请求的数据封装到新的请求中,然后再转发出去。然而我们在他封装之前读取了一次request body,而request body只能读取一次。因此就出现了上面的错误。
解决方案
对于上面的错误我们给出的解决方案是:
读取request body的时候,我们再封装一次request,转发出去
下面是我们的代码:
@Component
public class PostFilter extends AbstractNameValueGatewayFilterFactory { private static final String X_APP_ID_HEADER = "X-app-id";
public static final String X_FORWARDED_FOR = "X-Forwarded-For"; @Override
public GatewayFilter apply(NameValueConfig nameValueConfig) {
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())){//判断是否为POST请求
Flux<DataBuffer> body = request.getBody();
AtomicReference<String> bodyRef = new AtomicReference<>();//缓存读取的request body信息
body.subscribe(dataBuffer -> {
CharBuffer charBuffer = StandardCharsets.UTF_8.decode(dataBuffer.asByteBuffer());
DataBufferUtils.release(dataBuffer);
bodyRef.set(charBuffer.toString());
});//读取request body到缓存
String bodyStr = bodyRef.get();//获取request body
System.out.println(bodyStr);//这里是我们需要做的操作
DataBuffer bodyDataBuffer = stringBuffer(bodyStr);
Flux<DataBuffer> bodyFlux = Flux.just(bodyDataBuffer); request = new ServerHttpRequestDecorator(request){
@Override
public Flux<DataBuffer> getBody() {
return bodyFlux;
}
};//封装我们的request
}
return chain.filter(exchange.mutate().request(request).build());
};
} 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;
}
}
至此,该问题得到解决。
[spring cloud] [error] java.lang.IllegalStateException: Only one connection receive subscriber allowed.的更多相关文章
- Spring Cloud Hystrix java.lang.NoClassDefFoundError: org/aspectj/lang/JoinPoint 问题
环境:spring boot: 1.3.7 spring cloud : Brixton.SR5 <parent> <groupId>org.springframewo ...
- java.lang.IllegalStateException: Failed to load ApplicationContext selenium 异常 解决
WARN <init>, HHH000409: Using org.hibernate.id.UUIDHexGenerator which does not generate IETF R ...
- maven打包错误:java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.118 sec <<< FAILURE! - in ...
- java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
java.lang.IllegalStateException: Not allowed to create transaction on sharedEntityManager - use Spri ...
- Spring Scheduled定时任务报错 java.lang.IllegalStateException: Encountered invalid @Scheduled method 'xxx': For input string: "2S"
报错信息如下: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ding ...
- 【spring boot】【elasticsearch】spring boot整合elasticsearch,启动报错Caused by: java.lang.IllegalStateException: availableProcessors is already set to [8], rejecting [8
spring boot整合elasticsearch, 启动报错: Caused by: java.lang.IllegalStateException: availableProcessors ], ...
- spring低版本报错:java.lang.IllegalStateException: Context namespace element ‘annotation-config’ and its parser class [*] are only available on
参考来源:http://blog.csdn.net/sunxiaoyu94/article/details/50492083 使用spring低版本(2.5.6),使用jre 8发现错误: Unexp ...
- spring mvc处理http请求报错:java.lang.IllegalStateException: getInputStream() has already been called for this request
发送post请求到controller处理失败,报错日志如下: java.lang.IllegalStateException: getInputStream() has already been c ...
- java.lang.IllegalStateException: Active Spring transaction synchronization or active JTA transaction with specified [javax.transaction.TransactionManager] required
错误信息: java.lang.IllegalStateException: Active Spring transaction synchronization or active JTA trans ...
随机推荐
- lua的数据类型
Lua 是动态(弱)类型的语言,它有一下几种数据结构: nil(空) nil 类型表示一种没有任何有效值,它只有一个值 -- nil,例如打印一个没有赋值的变量,便会输出一个 nil 值: print ...
- O059、Backup Volume 操作
参考https://www.cnblogs.com/CloudMan6/p/5662236.html BackUp是将Volume备份到别的地方(备份设备),将来可以通过restore操作恢复. ...
- bus事件总线传值
import Vue from 'vue' var bus = new Vue() export default bus 监听事件: // header组件 <template> ...
- SQL*Loader 的使用sqlldr和sqluldr2方法详解
oracle数据导出工具sqluldr2可以将数据以csv.txt等格式导出,适用于大批量数据的导出,导出速度非常快.导出后可以使用oracle loader工具将数据导入.简介:Sqluldr2:专 ...
- Delphi MSComm控件的错误消息
- Docker_云计算技术简述
Docker官方网站 > https://www.docker.com/Docker博客 > https://www.docker.com/blog/Docker内容库 > http ...
- oracle下关于table的常用sql整理
创建表,create TABLE table( 列名称1 数据类型1, 列名称2 数据类型2, 列名称3 数据类型3, ......); eg: create table TABLE_24751( i ...
- c++ mfc和win32项目
win32项目是一个底层的窗口的实现过程,它采用的库仅仅是windows.h,我们通过winain作为函数的入口,然后经过窗口类的内容的填写,窗口的注册,创建,显示刷新,到最后的消息循环,这是一个wi ...
- 使用 Eclipse 构建的时候会出现 run as 中没有 maven package 选项
注:该方法来自我学习时别人分享的出现问题的解决方法,并没有亲自测试,仅供参考 是因为建的是普通 java 工程,需要把它转换成 maven project. 1.右键工程--maven--Disabl ...
- QTP(13)
练习1:Flight4a 要求: a.录制Flight4a登录+购票+退出业务流程 b.实现登录1次,购票3次,退出1次 c.对Fly From.Fly to.航班实现随机参数化 随机参数化:Rand ...