英文:
Spring WebFlux - a question about duplicating method invocation
问题
我使用了Spring Reactive框架创建了一个合成应用程序,以研究与Webflux一起提出的缓存机制。我注意到,当我使用指向第三方URL的WebClient
时,调用使用它的方法会调用两次,而当WebClient
指向我自己的端点时,每个请求只调用一次,与预期相符。
我想知道为什么会这样?
这是我页面抽象的代码,当webClient
与本地主机URL关联时,每个请求只调用一次getBody()
方法。但是,当webClient
与https://other.size关联时,此方法会被调用两次,因此我会看到两次log.info消息:
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("获取数据");
return res;
}
}
这是完整项目的链接:https://github.com/RassulYunussov/webluxmistery
英文:
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
得分: 1
感谢提供视频,非常有帮助。
因此,如果您在浏览器中访问/tengri
端点,您将会收到日志两次,我可以确认在我的机器上也看到了相同的行为。
然而,如果您使用curl
访问/tengri
,您只会收到一次日志记录。
此外,通过查看浏览器上的网络流量,我可以看到第二个 API 调用被发起到/tengri
端点。
在浏览器呈现 HTML 时,是否会触发一些附加逻辑,从而对/tengri
再进行一次调用?
英文:
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.
Is there some additional logic that will happen when the html is rendered by the browser that will make a 2nd call to /tengri
?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论