netty - 使用 Spring WebClient 时,连接被关闭,因为 HttpClientOperations Received last HTTP packet
问题描述
我正在使用 Spring WebClient 从我的服务器接收服务器发送事件(由 Spring SSEEmitter 发布)。它工作正常,但是,由于某种原因,我的服务器定期在新行中发布一个字符串“0”。发生这种情况时,WebClient 将关闭连接。
我挖了进去,打开Spring调试,发现如下信息:
+--------------------...+
| 0 1 2 3 4 5 ... |
| 30 0d 0a 0d 0a ...-|0.... |
[reactor.ipc.netty.http.client.HttpClientOperations:218] Received last HTTP packet
[reactor.ipc.netty.http.client.HttpClient:71] - USER_EVENT: [Handler Terminated]
[reactor.ipc.netty.channel.ChannelOperationsHandler:218] - Disposing context reactor.ipc.netty.channel.PooledClientContextHandler@45a97ad8
[reactor.ipc.netty.channel.PooledClientContextHandler:218] - Releasing channel:
[reactor.ipc.netty.resources.DefaultPoolResources:218] - Released, now 0 active connections
[reactor.ipc.netty.http.client.HttpClient:71] - READ COMPLETE
[reactor.ipc.netty.http.client.HttpClient:71] - READ COMPLETE
[reactor.ipc.netty.http.client.HttpClient:71] - CLOSE
[reactor.ipc.netty.http.client.HttpClient:71] - INACTIVE
[reactor.ipc.netty.http.client.HttpClient:71] - UNREGISTERED
很明显WebClient内部使用了Netty HttpClient,这个客户端把字符串“0”当成“lastHttpMessage”,然后关闭连接。
我的问题:
- 为什么 Netty 将“0”视为 http 连接的结束。
- 是否可以配置某物来修改此行为。
- WebClient 只能用 Netty 还是可以插别的东西?目前看来不可能。
解决方案
我发现如果我使用“重复”,Flux 将在连接完成后自动重新连接。甜的!
final Flux<Object> stream = WebClient
.create("http://localhost:8080/ssp")
.get().uri("/common/v1/eventstream")
.retrieve()
.bodyToFlux(ServerSentEvent.class)
.flatMap(e -> Mono.justOrEmpty(e.data()))
.repeat();
stream.subscribe(e -> System.out.println(e));