I started learning spring’s reactive http client WebClient
and im having trouble understanding contextual information between requests and responses. When using RestTemplate
this was easy to do with thread locals.
I want to implement a generic webclient that adds callId to the request and response logs automatically so i tried something like this which throws an error because “callId” is not in the context:
private WebClient createLoggingWebclient() {
return WebClient.builder()
.filter(addToCtx())
.filter(readCtx())
.baseUrl("https://localhost:8080")
.build();
}
private ExchangeFilterFunction readCtx() {
return ExchangeFilterFunction.ofResponseProcessor(
clientResponse ->
clientResponse.bodyToMono(String.class)
.flatMap(s ->
Mono.deferContextual(ctx -> {
// log response body and callId
log.info("callId: {}", (String)ctx.get(CALL_ID));
return Mono.just(clientResponse.mutate().body(s).build());
})
)
);
}
private ExchangeFilterFunction addToCtx() {
return ExchangeFilterFunction.ofRequestProcessor(
clientRequest ->
// log request body and callId
Mono.just(clientRequest).contextWrite(Context.of(CALL_ID, "123"))
);
}
What am i getting wrong and how can i implement this feature?