Spring WebFlux - a question about duplicating method invocation

514 views Asked by At

I've created a synthetic application using Spring Reactive framework to investigate caching mechanics, that is proposed with Webflux. What I've noticed, is that when I use a Webclient, that addresses to a third party URL, a method that uses it is called twice, whereas a WebClient, that addresses to my own endpoint is called only one time per request as expected.

I wonder why is it so?

Here is my code for page abstraction, when a webClient is associated with localhost URL, a method getBody() is called only once per request. But when webClient is associated with https://other.size, this method is invoked twice so I see log.info messages two times:

public class Page {

    private Mono<String> res;

    public Page(WebClient webClient, String url) {
        res = webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class)
                .cache();
    }
    public Mono<String> getBody() {
           log.info("getting data");
           return res;
    }
}

Here is a link to the full project: https://github.com/RassulYunussov/webluxmistery

1

There are 1 answers

1
Michael McFadyen On BEST ANSWER

Thanks for the video. It was really helpful.

So if you hit the /tengri endpoint from the browser, you will receive the logs twice and I can confirm I see the same behaviour on my machine.

However, if you hit /tengri using curl you only get the log line once.

Furthermore, looking into the network traffic on the browser I can see a 2nd api call being made to the /tengri endpoint.

Partial Network Traffic From http://localhost:8080/tengri

Is there some additional logic that will happen when the html is rendered by the browser that will make a 2nd call to /tengri?