使用 Mono.fromCallable 时获取 Mono 上下文
Getting Mono context when using Mono.fromCallable
我们使用 WebFilter 将 object 添加到 Mono.subscriberContext
。此 object 包含通过 HTTP headers.
传入的 trace-ids
chain.filter(exchange)
.subscriberContext(Context.of(SomeClass.class, contextObject))
然后我们使用以下代码在 Mono 中封装遗留 JDBC 调用:
Mono.fromCallable(() -> legacyDao.jdbcCall(contextObject)))
.timeout(Duration.ofMillis(timeout))
.subscribeOn(Schedulers.elastic());
我正在尝试访问 Mono.subscriberContext
以检索包含 trace-ids 的 object。这将在 DAO 调用中使用,以便在记录时将 trace-ids 添加到 MDC。
通常我们使用 doOnEach(signal -> ...)
从上下文中获取 object 并进行日志记录。
我知道 Spring Sleuth 是一个选项,但我们不想在这个阶段使用它。
正如 Simon Baslé 指出的那样,解决方案是用 Mono.subscriberContext
包装
Mono.subscriberContext().flatMap(context -> {
ContextObject contextObject = context.get(SomeClass.class);
return Mono.fromCallable(() -> legacyDao.jdbcCall(contextObject))
.timeout(Duration.ofMillis(timeout))
.subscribeOn(Schedulers.elastic());
});
我们使用 WebFilter 将 object 添加到 Mono.subscriberContext
。此 object 包含通过 HTTP headers.
chain.filter(exchange)
.subscriberContext(Context.of(SomeClass.class, contextObject))
然后我们使用以下代码在 Mono 中封装遗留 JDBC 调用:
Mono.fromCallable(() -> legacyDao.jdbcCall(contextObject)))
.timeout(Duration.ofMillis(timeout))
.subscribeOn(Schedulers.elastic());
我正在尝试访问 Mono.subscriberContext
以检索包含 trace-ids 的 object。这将在 DAO 调用中使用,以便在记录时将 trace-ids 添加到 MDC。
通常我们使用 doOnEach(signal -> ...)
从上下文中获取 object 并进行日志记录。
我知道 Spring Sleuth 是一个选项,但我们不想在这个阶段使用它。
正如 Simon Baslé 指出的那样,解决方案是用 Mono.subscriberContext
Mono.subscriberContext().flatMap(context -> {
ContextObject contextObject = context.get(SomeClass.class);
return Mono.fromCallable(() -> legacyDao.jdbcCall(contextObject))
.timeout(Duration.ofMillis(timeout))
.subscribeOn(Schedulers.elastic());
});