Hi everyone,

We all are aware that we sometimes need to add a connection and a read time-out attribute to a rest client to stop it from long wait for resources.

In spring boot, we can define a Bean to inject an object.

So, let’s jump into the code directly.

@Configuration
public class ProjectConfiguration {

  @LoadBalanced
  @Bean
  public WebClient.Builder webClientLoadBalanced() {
    return WebClient.builder();
  }
  
  @Primary
  @Bean(name = "WebClientWithTimeout")
  public WebClient.Builder webClient() {
    String connectionProviderName = "customConnectionProvider";
      int maxConnections = 20;
      int acquireTimeout = 20;
      ConnectionProvider connectionProvider = ConnectionProvider.builder(connectionProviderName)
              .maxConnections(maxConnections)
              .pendingAcquireTimeout(Duration.ofSeconds(acquireTimeout))
              .build();

      HttpClient httpClient = HttpClient.create(connectionProvider)
              .tcpConfiguration(tcpClient -> tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
              .doOnConnected(connection -> {
                  connection.addHandlerLast(new ReadTimeoutHandler(5));
                  connection.addHandlerLast(new WriteTimeoutHandler(5));
              }));
      return WebClient.builder().clientConnector(new ReactorClientHttpConnector(httpClient));
  }
}

In this example, 2 beans of Webclient has been declared. One is loadbalaced. Another one is the primary one – with @Primary annotation. The main webclient is the primary one and it has timeout attributes.

 

That’s it.

Feedback / comments are welcome.

Have a nice day ahead.

 

 

Loading