Skip to content

Instantly share code, notes, and snippets.

@cherniag
Last active December 1, 2020 13:35
Show Gist options
  • Save cherniag/7e20d791a2bc22b382ef3c6573fd3ce4 to your computer and use it in GitHub Desktop.
Save cherniag/7e20d791a2bc22b382ef3c6573fd3ce4 to your computer and use it in GitHub Desktop.
Load balanced Spring WebClient + setting Netty read and connect timeouts
// https://projectreactor.io/docs/netty/snapshot/reference/index.html
@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder(ExchangeStrategies exchangeStrategies, ClientHttpConnector clientHttpConnector) {
return WebClient.builder()
.clientConnector(clientHttpConnector)
// .filter(new LoadBalancerExchangeFilterFunction(loadBalancerClient)) // in case without @LoadBalanced annotation, loadBalancerClient comes from context
.exchangeStrategies(exchangeStrategies);
}
@Bean
public ExchangeStrategies exchangeStrategies() {
return ExchangeStrategies.builder()
.codecs(configurer -> configurer
.defaultCodecs()
.maxInMemorySize(1024 * 1024 * 2)) // default is 256KB
.build();
}
@Bean
public ClientHttpConnector clientHttpConnector(TcpClient tcpClient) {
return new ReactorClientHttpConnector(HttpClient.from(tcpClient));
}
@Bean
public TcpClient tcpClient(NettyConfig nettyConfig) {
return TcpClient.create()
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, nettyConfig.getConnectTimeout())
.doOnConnected(connection -> connection.addHandlerLast(new ReadTimeoutHandler(nettyConfig.getReadTimeout(), TimeUnit.MILLISECONDS)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment