How to correctly simulate latency with Spring WebClient

615 Views Asked by At

I want to add code that would simulate latency in my WebClient calls so I could ensure my timeouts/retries/etc are working correctly.

Since WebClient is reactive and uses a thread pool, it seems like Thread.sleep would block the thread in a way that WebClient wouldn't typically be blocked in real usage.

Is there a better way to simulate that latency?

(Inspired by https://github.com/fletchgqc/chaos-monkey-spring-boot/pull/2/files#diff-7f7c533cc2b344aa04848a17d0eff0cda404a5ab3cc55a47bba9ed019fba82e3R9

public class LatencyInducingRequestInterceptor implements ClientHttpRequestInterceptor {

  public ClientHttpResponse intercept(
      HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    ClientHttpResponse response = execution.execute(request, body);

    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      // do nothing
    }

    return response;
  }
}
1

There are 1 best solutions below

0
On

The answer is to use delayElement (The code I had posted above was for RestTemplate, that explains why Thread.sleep was used.

  ExchangeFilterFunction latencyAddingFilterFunction =
      (clientRequest, nextFilter) -> {
        return nextFilter.exchange(clientRequest).delayElement(Duration.ofSeconds(2));
      };