【问题标题】:How to forward reactive context in to WebClient?如何将反应式上下文转发到 WebClient?
【发布时间】:2022-10-21 18:13:53
【问题描述】:

我有 MDC 上下文,它用于记录。我正在从调度程序启动反应链并生成上下文:

private void generateMDCcontext() {
        UUID uuid = UUID.randomUUID();
        MDC.put("requestid", uuid.toString());
}

接下来,我有用于外部 http 请求的 WebClient,在请求期间我丢失了上下文。 这是构造函数中的初始化 WebClient:

this.webClient = WebClient.create().mutate()
                .clientConnector(new JettyClientHttpConnector(httpClient))
                .build();

在下面我发送请求:

log.info("Before request");
return webClient.post()
                .uri(addr)
                .acceptCharset(StandardCharsets.UTF_8)
                .contentLength(BODY_LENGTH)
                .retrieve()
                .onStatus(HttpStatus::isError, response -> Mono.error(...)//custom error
                .bodyToMono(CustomResponse.class)
                .timeout(timeuot)
                .doOnError(e -> log.error("Error during request ");
                )
                .onErrorMap(e -> {
                return customExceptoin;
                })
                .doOnSuccess(resp -> {
                log.info("Success, response: {}", resp == null ? null : resp);
                });
    }

如果外部服务器有问题,我正在等待下一个结果:

2022-07-28 15:01:20.128 requestid[7fa703d7-5d99-4502-b3cf-0e4737a2d7be] INFO Before request
2022-07-28 15:01:20.228 requestid[7fa703d7-5d99-4502-b3cf-0e4737a2d7be] ERROR Error during request
2022-07-28 15:01:20.328 requestid[7fa703d7-5d99-4502-b3cf-0e4737a2d7be] ERROR CustomExceptiomMsg

但是我在 webClient 调用中获取了带有空请求 ID 的日志:

2022-07-28 15:01:20.128 requestid[7fa703d7-5d99-4502-b3cf-0e4737a2d7be] INFO Before request
2022-07-28 15:01:20.228 requestid[] ERROR Error during request
2022-07-28 15:01:20.328 requestid[] ERROR CustomExceptiomMsg

我可以通过在每个 lambda 中的 webClient 和 MDC.setContextMap(copyOfContextMap) 之前使用 MDC.getCopyOfContextMap() 来修复它,但我正在寻找更正确的解决方案

【问题讨论】:

    标签: java reactive-programming spring-webflux mdc


    【解决方案1】:

    你能解决这个问题吗?你是如何解决这个问题的?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-09
      • 1970-01-01
      • 2021-02-12
      • 2020-08-05
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 2020-11-27
      相关资源
      最近更新 更多