You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Webflux如何在doOnNext()中获取上下文关联ID?

如何在Reactor的doOnNext中获取上下文里的关联ID?

我通过contextWrite将关联ID(correlation ID)存储在上下文中,希望在实现日志逻辑的doOnNext()方法中获取并使用该ID。

以下是我最初的实现代码:

Mono.just("message")
   ...
   .doOnNext(it -> Mono.deferContextual(ctx -> Mono.just(ctx)
      .doOnNext(c -> log.info("correlation-id: "+ c.get(CORRELATION_ID))))) 
   .subscribe();

这是唯一的实现方式吗?我感觉这种写法有些奇怪。我仍在学习中,查阅了Reactor文档的上下文部分,但未找到类似场景的实现方法。

更新1

我实现了更简洁的写法(无需两次调用Mono.just()):

Mono.deferContextual(ctx ->
   Mono.just("message")
      ...
      .doOnNext(it -> log.info("correlation-id: " + ctx.get(CORRELATION_ID)))
);

不确定这是否是最佳实践,但比之前的写法更优。

更新2

深入研究代码和文档后,我发现Mono.deferContextual()会返回一个Mono(之前忽略了这一点)。因此第一种场景应使用flatMap()替代doOnNext(),需重构代码使其在flatMap()中返回接收的对象,以模拟doOnNext()的功能。

更新3

我最终采用transformDeferredContextual()实现了代码。根据Reactor文档:

to access the context from the middle of an operator chain, use transformDeferredContextual(BiFunction)

应用到我的场景中:

Mono.just("message")
   ...
   .transformDeferredContextual((originalMono, context) -> {
         log.info("correlation-id: " + context.get(CORRELATION_ID));
         
         return originalMono;
   })
   .subscribe();

这种写法仍有些奇怪,但目前看来是最佳方案。


内容的提问来源于stack exchange,提问作者Gabriel Magalhães

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 18:45:49