Class RequestContextMDCBridge
java.lang.Object
com.loomcache.server.context.RequestContextMDCBridge
Bridge to synchronize ScopedValue-based RequestContext with SLF4J's MDC.
Purpose
This class demonstrates the gradual migration path from ThreadLocal-based MDC to ScopedValue-based RequestContext. It provides utilities to: - Sync RequestContext values to MDC for compatibility with existing loggers - Demonstrate how to gradually adopt ScopedValues in the codebaseMigration Strategy
- Step 1: Introduce RequestContext alongside MDC (this bridge)
- Step 2: Use ScopedValue.run() or call() to bind context
- Step 3: Optionally sync to MDC via this bridge for logger compatibility
- Step 4: Update logback.xml to consume RequestContext instead of MDC
- Step 5: Remove MDC.put/remove calls once all logging uses RequestContext
Usage Example
// Old way (ThreadLocal/MDC):
MDC.put("nodeId", "node-1");
MDC.put("requestId", "123");
try {
// ... operation ...
} finally {
MDC.remove("nodeId");
MDC.remove("requestId");
}
// New way (ScopedValue + bridge):
var context = RequestContext.newScope()
.nodeId("node-1")
.correlationId(123L);
context.run(() -> {
RequestContextMDCBridge.syncToMDC(); // Optional: for logger compatibility
// ... operation ...
RequestContextMDCBridge.clearMDC();
});
- Since:
- 1.0
- See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic voidclearMDC()Clear all MDC values that were set by syncToMDC().static booleanCheck if any RequestContext values are currently bound.static voidSynchronize current RequestContext values to MDC.
-
Constructor Details
-
RequestContextMDCBridge
public RequestContextMDCBridge()
-
-
Method Details
-
syncToMDC
public static void syncToMDC()Synchronize current RequestContext values to MDC.Call this within a RequestContext.newScope().run() block to make context available to loggers that expect MDC values.
RequestContext.newScope() .nodeId("node-1") .correlationId(123L) .run(() -> { RequestContextMDCBridge.syncToMDC(); log.info("Processing request"); // MDC values available RequestContextMDCBridge.clearMDC(); }); -
clearMDC
public static void clearMDC()Clear all MDC values that were set by syncToMDC().Call this in a finally block or at the end of a scope to clean up MDC.
-
hasContext
public static boolean hasContext()Check if any RequestContext values are currently bound.- Returns:
- true if at least one context value is set
-