【问题标题】:How to correctly simulate latency with Spring WebClient如何使用 Spring WebClient 正确模拟延迟
【发布时间】:2021-06-17 03:05:32
【问题描述】:

我想添加代码来模拟我的 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;
  }
}

【问题讨论】:

    标签: spring-boot spring-webclient spring-boot-chaos-monkey


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 2019-02-21
      • 2016-06-30
      相关资源
      最近更新 更多