1
votes

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

1
Can you give a full minimal reproducible example? I'd expect logRequest() to get called immediately, but I'd expect the "business logic for callback" you've marked to be executed just as the request is made, not when the mono is created.Michael Berry
@MichaelBerry you are right logRequest() is called immediately . however business logic is also called in the call to retrieve() method. i want to delay it till just before the request execution. business logic is a log statement. It logs the timestamp when the request started executing e.g. log.info("start time is ",currtimeinmillis)Dumbledore
i dont really understand what it is you want to doToerktumlare

1 Answers

1
votes

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.