ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

spring – 基于Servlet的web-mvc应用程序中的RestTemplate与WebClient优势

2019-05-22 16:05:52  阅读:227  来源: 互联网

标签:spring-mvc spring spring-webflux


我正在寻找下面声明中粗体文本的澄清(我仅为上下文提供了完整的段落):

The RestTemplate is not a good fit for use in non-blocking applications, and therefore Spring WebFlux application should always use the WebClient. The WebClient should also be preferred in Spring MVC, in most high concurrency scenarios, and for composing a sequence of remote, inter-dependent calls.

在这里找到:https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html

特别是对于Spring MVC应用程序使用WebClient而不是RestTemplate有什么好处?如果使用apache HttpClient和PoolingHttpClientConnectionManager配置了具有适当配置的连接和套接字配置的RestTemplate,WebClient将如何实现更高的规模?

解决方法:

WebClient是非阻塞的,而RestTemplate是阻塞/同步的.如果您将非阻塞WebFlux API与阻塞库一起使用,那么您实际上将其转变为阻塞API.

将RestTemplate想象为实际为每个事件创建一个新线程,而不是创建一个任务的WebClient(就像在队列中一样,这实际上是Reactor为您在幕后管理的内容).
如果每个非阻塞任务都有一个阻塞调用支持它,你将很快达到线程饥饿(就像每个RestTemplate的情况一样;注意委托给ConnectionManager仍在进行阻塞调用).
另一方面,任务将由反应框架排队,并在您拥有适当的资源时执行.

为什么在Spring MVC中使用WebClient

WebClient是非阻塞的!您可以使用它的所有Flux功能(pub-sub,backpressure等).这有助于节省资源(即您使用更少的线程和更少的内存),Reactor将允许您最大限度地使用您未使用的线程.
这里的问题实际上并不是“为什么我应该使用WebClient”和Spring MVC,问题是“我为什么要在我的应用程序中使用被动/非阻塞”框架.在这个问题的互联网上有很多例子(here’s one)和它的答案.

如果您想使用非反应性非阻塞构造,Mono和Flux也可以返回Java 8 CompletableFuture.

为什么将WebClient与WebFlux一起使用

从您referenced in that documentation页面看到此引用:

WebClient uses the same codecs as WebFlux server applications do, and
shares a common base package, some common APIs, and infrastructure
with the server functional web framework. The API exposes Reactor Flux
and Mono types

关键是WebClient使用与Flux相同的反应性非阻塞类型.这就是为什么集成这么好,你得到了很好的任务功能.例如(我从that doc借了一大块代码):

WebClient client = WebClient.create("http://example.org");
Mono<Void> result = client.post()
        .uri("/persons/{id}", id)
        .contentType(MediaType.APPLICATION_JSON)
        .body(personMono, Person.class)
        .retrieve()
        .bodyToMono(Void.class);

看看这段代码如何产生Mono?这是WebFlux构建的反应式构造,这就是你将它与框架一起使用的原因.例如,你实际上可以return that Mono reactively in a Controller call

@PostMapping("/person")
Mono<Void> create(@RequestBody Publisher<Person> personStream) {
     // ... above code could go here...
     return result; 
}

这种类型的事情是他们说你应该将WebClient与WebFlux库一起使用的关键原因.

标签:spring-mvc,spring,spring-webflux
来源: https://codeday.me/bug/20190522/1152694.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有