Reputation: 63
I am using spring-webflux 5.1.7-RELEASE. I want to trigger the callback for webclient just before the request is sent. The code for this is:
ExchangeFilterFunction logRequest (SomeLogObject someLogObject) {
return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
/**
business logic for callback goes here
*/
return Mono.just(clientRequest);
});
}
//code for plugging in logRequest callback (at some othe place)
WebClient webClient = WebClient
.builder()
.clientConnector(new ReactorClientHttpConnector(HttpClient.from(tcpClient)))
.baseUrl(baseURL)
.filters(exchangeFilterFunctions -> exchangeFilterFunctions.add(logRequest(someLogObject)))
.build();
webClient
.get()
.uri(uriBuilder -> uriBuilder.path("some_uri_path").queryParams(queryParam).build())
.header("some_header_key", "some_header_value")
.retrieve().bodyToMono(String.class);
Here the logRequest is triggered in beginning itself (much before the request is triggered). As per my debugging I found that it gets triggered when retrieve() is called.
Is there a way to ensure that logRequest gets triggered immediately before the request is sent and NOT when the mono is created?
Thanks in advance
Upvotes: 1
Views: 1230
Reputation: 1181
I think you are looking for the following change:
ExchangeFilterFunction logRequest (SomeLogObject someLogObject){
return ExchangeFilterFunction.ofRequestProcessor(clientRequest ->
Mono.defer(() -> {
/**
business logic for callback goes here
*/
return Mono.just(clientRequest);
})
);
}
Mono.defer()
will delay code execution until the real request.
Upvotes: 2