如何仅记录来自 WebClient 的 POST ant PATCH 请求

问题描述

我正在注册过滤器以记录来自 WebClient 的响应,但我只想记录 POST 和 PATCH 请求(没有大量我不感兴趣的 GET 请求)。如何仅记录特定的 POST 和 PATCH 响应?

WebClient bean:

  @Bean
  public WebClient sfWebClient() {
    return WebClient.builder()
        .filter(logResponse())
        .build();
  }

logResponse 过滤器:

  ExchangeFilterFunction logResponse() {
    return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
      if (log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Request finished with the status: ").append(clientResponse.statusCode());
        log.debug(sb.toString());
      }
      return Mono.just(clientResponse);
    });
  }

解决方法

我认为您可以像这样实现自己的 ExchangeFilterFunction:

WebClient.builder().filter((request,next) ->
        next.exchange(request).map(response -> {
            if ((request.method() == HttpMethod.POST || request.method() == HttpMethod.PATCH) && log.isDebugEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("Request finished with the status: ").append(response.statusCode());
                log.debug(sb.toString());
            }
            return response;
        });
    );