Reputation: 1688
@LoadBalanced
@Bean
public RestTemplate getRestTemplate()
{
HttpComponentClientHttpRequestFactory clientHttpRequestFactory=
new HttpComponentClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(5000);
return new RestTemplate(clientHttpRequestFactory);
}
I have to replace the above code with WebClient
@LoadBalanced
@Bean(name = "WebClient")
public WebClient.Builder getWebClientBuilder()
{
// create HttpComponentClientHttpRequestFactory instance and it can not be
//passed to builder method as an argument
return WebClient.builder();
}
I need an alternative to set timeout with WebClient.
Upvotes: 1
Views: 1037
Reputation: 2297
If you want a timeout for a specific request you can do something like:
webClient.get()
.uri("/employees")
.retrieve()
.bodyToFlux(Employee.class)
.timeout(Duration.ofMillis(10_000))
If instead of this you want a timeout to be applied to all the request you can build your web client like this:
@Bean
public WebClient getWebClient()
{
HttpClient httpClient = HttpClient.create()
.tcpConfiguration(client ->
client.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
.doOnConnected(conn -> conn
.addHandlerLast(new ReadTimeoutHandler(10))
.addHandlerLast(new WriteTimeoutHandler(10))));
ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient.wiretap(true));
return WebClient.builder()
.baseUrl("http://localhost:3000")
.clientConnector(connector)
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
}
}
you can see it here
https://howtodoinjava.com/spring-webflux/webclient-set-timeouts/
Upvotes: 1