Spring WebFlux WebClient timeout() 和 exchange()
Spring WebFlux WebClient timeout() and exchange()
我有类似于以下示例的代码:
Mono<ResponseEntity<String>> result = webClient
.post()
.body(Mono.just(command), MyCommand.class)
.exchange()
.timeout(calculateTimeout(command))
.flatMap(clientResponse -> clientResponse.toEntity(String.class));
When using exchange() you must always use any of the body or toEntity methods of ClientResponse to ensure resources are released and to avoid potential issues with HTTP connection pooling. You can use bodyToMono(Void.class) if no response content is expected. However keep in mind that if the response does have content, the connection will be closed and will not be placed back in the pool.
问题:如果上面代码中的 timeout(...) 触发了 TimeoutException,我是否必须明确地做一些事情来确保所有资源都被正确释放或者上面的代码是否足够?我想避免这里发生内存泄漏。
在这种情况下,我认为这不是问题。
触发后,timeout
将 cancel()
上游,有效地关闭连接并且不将其返回到连接池。您不需要在这里做任何特别的事情,也不会有内存泄漏(除了已经位于反应器内部队列中的缓冲区,这是一个问题 Spring 框架将在 SPR-17025 中解决)。
我有类似于以下示例的代码:
Mono<ResponseEntity<String>> result = webClient
.post()
.body(Mono.just(command), MyCommand.class)
.exchange()
.timeout(calculateTimeout(command))
.flatMap(clientResponse -> clientResponse.toEntity(String.class));
When using exchange() you must always use any of the body or toEntity methods of ClientResponse to ensure resources are released and to avoid potential issues with HTTP connection pooling. You can use bodyToMono(Void.class) if no response content is expected. However keep in mind that if the response does have content, the connection will be closed and will not be placed back in the pool.
问题:如果上面代码中的 timeout(...) 触发了 TimeoutException,我是否必须明确地做一些事情来确保所有资源都被正确释放或者上面的代码是否足够?我想避免这里发生内存泄漏。
在这种情况下,我认为这不是问题。
触发后,timeout
将 cancel()
上游,有效地关闭连接并且不将其返回到连接池。您不需要在这里做任何特别的事情,也不会有内存泄漏(除了已经位于反应器内部队列中的缓冲区,这是一个问题 Spring 框架将在 SPR-17025 中解决)。