Reputation: 525
I am currently using Webclient of spring-webflux package to make synchronous REST calls.
But the time taken to mae the first request is longer than the time taken by RestTemplate.
I have observed that the successive calls take much lesser time and more or less same to that of RestTemplate.
Is there a solution to decrease the initial lag for Webclient?
Upvotes: 1
Views: 2025
Reputation: 11
I followed the recommended method mentioned in the official documentation and tried using:
HttpClient client = HttpClient.create();
client.warmup().block();
However, this approach didn't result in a significant latency reduction. Then I used Jetty as a replacement for the default Netty dependency along with the WebClient.
To implement this, you need to add the following dependencies to your build.gradle or equivalent:
implementation 'org.eclipse.jetty:jetty-client'
implementation 'org.eclipse.jetty:jetty-reactive-httpclient'
Then, configure the WebClient bean with Jetty settings to call your external APIs:
@Bean
public WebClient webClient() throws Exception {
SslContextFactory.Client sslContextFactory = new SslContextFactory.Client();
HttpClient httpClient = new HttpClient(sslContextFactory);
httpClient.setFollowRedirects(false);
httpClient.setConnectTimeout(timeout); // ensure you've defined 'timeout'
httpClient.start();
final ClientHttpConnector connector = new JettyClientHttpConnector(httpClient);
return WebClient.builder().clientConnector(connector).build();
}
By using Jetty with WebClient, I noticed an improvement in performance. Hope this would be helpful for anybody experiencing similar latency issues.
Upvotes: 1
Reputation: 2282
By default, the initialization of the HttpClient
resources happens on demand. This means that the first request absorbs the extra time needed to initialize and load:
You can preload these resources - check this documentation
Things that cannot be preloaded are:
Upvotes: 3