0

我想在我的 WebClient 调用中添加模拟延迟的代码,这样我就可以确保我的超时/重试/等工作正常。

由于 WebClient 是反应式的并且使用线程池,因此它似乎Thread.sleep会以 WebClient 在实际使用中通常不会被阻塞的方式阻塞线程。

有没有更好的方法来模拟这种延迟?

(灵感来自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;
  }
}
4

1 回答 1

0

答案是使用delayElement(我上面发布的代码是 for RestTemplate,这解释了为什么Thread.sleep使用。

  ExchangeFilterFunction latencyAddingFilterFunction =
      (clientRequest, nextFilter) -> {
        return nextFilter.exchange(clientRequest).delayElement(Duration.ofSeconds(2));
      };
于 2021-03-20T22:36:56.753 回答