How to set a connect/read timeout in the Spring's RestClient
?
This client has been added in the Spring Framework 6.1.
How to set a connect/read timeout in the Spring's RestClient
?
This client has been added in the Spring Framework 6.1.
You could create a HttpComponentsClientHttpRequestFactory where you will set connection and read timeout and then you will be able to set it to RestClient
using provided builder.
public Object exampleMethod(Object object) {
RestClient restClient = RestClient
.builder()
.requestFactory(getClientHttpRequestFactory())
.build();
//usage of restClient with timeout.
restClient.get();
}
private ClientHttpRequestFactory getClientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(100);
clientHttpRequestFactory.setConnectionRequestTimeout(70);
return clientHttpRequestFactory;
}
In case anyone is also trying to take advantage of Spring's SslBundle
, defining it all in a ClientHttpRequestFactorySettings
object is what worked for me:
@Bean
public RestClient restClient(RestClient.Builder restClientBuilder, SslBundles sslBundles) {
ClientHttpRequestFactorySettings requestFactorySettings = new ClientHttpRequestFactorySettings(
Duration.ofSeconds(30),
Duration.ofSeconds(30),
sslBundles.getBundle("mybundle"));
return restClientBuilder
.requestFactory(ClientHttpRequestFactories.get(requestFactorySettings))
.build();
}
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS.withConnectTimeout(Duration.ofSeconds(30)).withReadTimeout(Duration.ofSeconds(30));
–
Pun bufferRequestBody
value are deprecated. It looks like the one used here is not –
Marcellusmarcelo I don't believe there is a generic way to set timeouts.
Just a bit of caution when using SSLBundles.
RestClient.Builder builder;
builder.apply(restClientSsl.fromBundle("myBundle"));
creates a new ClientHttpRequestFactory, you will lose all timeout settings already set on your ClientHttpRequestFactory.
Rather set the SSL bundle like this:
ClientHttpRequestFactorySettings settings;
ClientHttpRequestFactorySettings settings = ClientHttpRequestFactorySettings.DEFAULTS
.withConnectTimeout(Duration.ofMillis(30000))
.withReadTimeout(Duration.ofMillis(30000))
.withSslBundle(sslBundles.getBundle("myBundle"));
In RestClientSsl class there is a comment.
NOTE: Apply SSL configuration will replace any previously configured ClientHttpRequestFactory. If you need to configure ClientHttpRequestFactory with more than just SSL consider using a ClientHttpRequestFactorySettings with ClientHttpRequestFactories.
© 2022 - 2025 — McMap. All rights reserved.
HttpComponentsClientHttpRequestFactory
is from there. Is there another, more generic way to set timeouts? – Shingly