java / expert
Snippet
Manual MDC Context Propagation in Project Reactor
In reactive Spring applications, ThreadLocal-based MDC context is lost during thread switches. This pattern uses Reactor Hooks to lift context from the Subscriber's Context into the MDC map on every operator execution.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class MDCContextLifter<T> implements CoreSubscriber<T> {private final CoreSubscriber<T> coreSubscriber;public MDCContextLifter(CoreSubscriber<T> coreSubscriber) {this.coreSubscriber = coreSubscriber;}@Overridepublic void onNext(T t) {copyToMDC(coreSubscriber.currentContext());coreSubscriber.onNext(t);}@Overridepublic Context currentContext() {return coreSubscriber.currentContext();}private void copyToMDC(Context context) {if (context.hasKey(MDC_KEY)) {MDC.setContextMap(context.get(MDC_KEY));}}}
spring
Breakdown
1
public class MDCContextLifter<T> implements CoreSubscriber<T>
Implements the core subscriber interface to intercept signal emissions.
2
copyToMDC(coreSubscriber.currentContext());
Extracts the context map from the reactive stream and applies it to the current thread's MDC.
3
return coreSubscriber.currentContext();
Ensures the context is passed upstream correctly through the operator chain.