【问题标题】:Spring WebClient how to log each retry at INFO level?Spring WebClient如何在INFO级别记录每次重试?
【发布时间】:2021-11-03 21:53:36
【问题描述】:

我有以下 WebClient - 对 localhost:8090 进行 http 调用 - 定义了 bean:

@Configuration
class WebClientConfig {
    @Bean
    public WebClient webClientBean() {
        return WebClient.create("http://localhost:8090");
    }
}

然后调用另一个服务(8090):

Response response = requestBodySpec
        .retrieve()
        .bodyToMono(Response.class)
        .timeout(Duration.ofSeconds(5))
        .retry(2L)
        .doOnSuccess(res -> log.info(res))
        .doOnError(err -> log.error(err))
        .block();

我看到超时后的错误:

java.util.concurrent.TimeoutException: 'flatMap' 中 5000 毫秒内没有观察到任何项目或终端信号

但是我没有看到我指定的另外 2 次重试的日志;它们仅在我打开 TRACE 时可见:

TRACE 2120 --- [nio-8080-exec-1] o.s.w.r.f.client.ExchangeFunctions : [9c7e1e0] HTTP POST http://localhost:8090/test, headers={masked}

有什么方法可以在发生重试时记录事件?类似于上面的日志,除了我必须 INFO 记录它。

【问题讨论】:

    标签: spring spring-boot spring-webflux spring-webclient


    【解决方案1】:

    您可以尝试指定 RetrySpec 来代替,这样可以更好地控制重试行为并为执行非阻塞操作提供“回调”。

    假设您的记录器是非阻塞的,您可以执行以下操作:

    RetryBackOffSpec retrySpec = Retry.fixedDelay(2L, Duration.ofMillis(25))
                .doAfterRetry(signal -> log.info("Retry number {}", signal.totalRetries()));
    
    Response response = requestBodySpec
            .retrieve()
            .bodyToMono(Response.class)
            .timeout(Duration.ofSeconds(5))
            .retry(retrySpec)
            .doOnSuccess(res -> log.info(res))
            .doOnError(err -> log.error(err))
            .block();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 2018-10-17
      • 2019-09-09
      • 2019-05-30
      • 2018-02-19
      • 2017-10-29
      相关资源
      最近更新 更多