Learn how to seamlessly propagate context through a reactive stream in your project using Project Reactor, an essential skill for modern Java developers working with reactive programming models.
Mono<DemoClass> demoClassMono = Mono.just(demoObject)
// Add context to MDC (Mapped Diagnostic Context) for logging purposes on each signal π
.doOnEach(signal -> {
logUtil.addToMdc(signal.getContextView());
})
// Transform the Mono stream by applying a function to each item emitted π
.transform(demoClassMono1 -> {
log.info("inside main post init {}", demoClassMono1.toString());
return another.anotherDemoProcess(demoClassMono1);
})
// Write context information by adding header details to the Reactor context β
.contextWrite(context -> {
return context.putAllMap(headerDetails);
});
Key Concepts Explained π
.doOnEach((signal) -> {...})
: This operator allows for side-effects, such as logging, to be performed for each signal (onNext, onError, onComplete) in the stream. UtilizinglogUtil.addToMdc(signal.getContextView())
ensures that every emitted item enriches the Mapped Diagnostic Context (MDC), making it easier to trace and debug reactive chains. π.contextWrite(context -> {...})
: By leveraging this operator, developers can modify the context propagated down the stream. Adding key-value pairs from theheaderDetails
map into the Reactor context withcontext.putAllMap(headerDetails)
is a powerful way to include essential metadata, like request IDs or user tokens, throughout the reactive pipeline. π§
Why It Matters in Reactive Programming π
Understanding and implementing context propagation in reactive programming is pivotal for maintaining a clear and traceable execution flow, especially in complex, asynchronous systems. These techniques improve debugging, logging, and the management of metadata across asynchronous boundaries, enhancing the overall reliability and maintainability of applications built with Project Reactor.
here is a Git repo for an example
Git repo for context propagation
Top comments (0)