Add close() method on HTTP client response

Before this commit, there was no way to signal the HTTP client that we
were done consuming the response. Without that, the underlying client
library cannot know when it is safe to release the associated resources
(e.g. the HTTP connection).

This commit adds new `close()` methods on both `ClientHttpResponse`
and `ClientResponse`. This methods is non-blocking and its behavior
depends on the library, its configuration, HTTP version, etc.

At the `WebClient` level, `close()` is called automatically if we
consume the response body through the `ResponseSpec` or the
`ClientResponse` itself.

Note that it is *required* to call `close()` manually otherwise; not
doing so might create resource leaks or connection issues.

Issue: SPR-15920
This commit is contained in:
Brian Clozel
2017-09-06 14:06:56 +02:00
parent ba6b617bd5
commit 16f3f8d28f
11 changed files with 238 additions and 16 deletions

View File

@@ -55,6 +55,7 @@ public class MockClientHttpResponse implements ClientHttpResponse {
private final DataBufferFactory bufferFactory = new DefaultDataBufferFactory();
private boolean closed = false;
public MockClientHttpResponse(HttpStatus status) {
Assert.notNull(status, "HttpStatus is required");
@@ -62,6 +63,7 @@ public class MockClientHttpResponse implements ClientHttpResponse {
}
@Override
public HttpStatus getStatusCode() {
return this.status;
}
@@ -71,6 +73,7 @@ public class MockClientHttpResponse implements ClientHttpResponse {
return this.headers;
}
@Override
public MultiValueMap<String, ResponseCookie> getCookies() {
return this.cookies;
}
@@ -94,10 +97,23 @@ public class MockClientHttpResponse implements ClientHttpResponse {
return this.bufferFactory.wrap(byteBuffer);
}
@Override
public Flux<DataBuffer> getBody() {
if (this.closed) {
return Flux.error(new IllegalStateException("Connection has been closed."));
}
return this.body;
}
@Override
public void close() {
this.closed = true;
}
public boolean isClosed() {
return this.closed;
}
/**
* Return the response body aggregated and converted to a String using the
* charset of the Content-Type response or otherwise as "UTF-8".