0

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

Vy Do
  • 46,709
  • 59
  • 215
  • 313
  • I checked out your project, ran your app and invoked both endpoints. The log line "getting data" was only logged once per api call for both endpoints. The log line is logged on every api call, even the ones that should be cached but this is expected behaviour based on the code that is there. – Michael McFadyen Oct 11 '20 at 16:43
  • Sounds strange, so I double checked the project and had the same result - double invocation of method for external resource. As a proof - I've recorded a video of this:) https://youtu.be/aNPhRAzJypQ As for java version: openjdk version "14.0.1" 2020-04-14 OpenJDK Runtime Environment AdoptOpenJDK (build 14.0.1+7) OpenJDK 64-Bit Server VM AdoptOpenJDK (build 14.0.1+7, mixed mode, sharing) – Rassul Yunussov Oct 12 '20 at 15:12

1 Answers1

1

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?

Michael McFadyen
  • 2,675
  • 11
  • 25
  • I just didn't bother about probable side effects of contents that I load. Perhaps this page calls some JS to make a second request. curl - is a better way to test everything. Thank you! – Rassul Yunussov Oct 14 '20 at 14:29