问题描述
我们有一个即将投入生产的 Spring 项目.目前,该项目使用的是Apache Http Client
.有一个使用 RestTemplate
作为 HttpClient
的想法.
we have a Spring project that is about to go into production. Currently, the project is using Apache Http Client
. There is a thought of using RestTemplate
as HttpClient
.
我正在四处寻找使用 RestTemplate
优于 Apache
的任何显着优势.此外,了解 HTTP 传输在 RestTemplate 的实现中做了什么会很有趣.Apache Http Client 已被多个团体使用多年,口碑良好.
I am digging around to see any notable advantage of using RestTemplate
over Apache's
. Also, it would be interesting to know what HTTP transport does RestTemplate in its implementation. Apache Http Client has been used by several groups for many years and has a good reputation.
我们是否会冒险转向 RestTemplate
?
would we be risking moving to RestTemplate
?
此外,此博客指出需要为生产配置 RestTemplate,虽然配置很小.
Further, this blog points that RestTemplate needs to be configured for production, although the configuration is minimal.
谢谢
推荐答案
RestTemplate 和 HttpClient 不在同一抽象级别上运行.
RestTemplate and HttpClient don't operate at the same abstraction level.
HttpClient 是使用 HTTP 进行通信的通用库,而 RestTemplate 是更高级别的抽象,处理实体的 JSON/XML 转换等.
HttpClient is a general-purpose library to communicate using HTTP, whereas RestTemplate is a higher-level abstraction, dealing with JSON/XML transformation of entities, etc.
RestTemplate 委托给 ClientHttpRequestFactory 和 这个接口的一个实现使用了Apache的HttpClient.
RestTemplate delegates to a ClientHttpRequestFactory, and one of the implementations of this interface uses Apache's HttpClient.
因此,如果目标是与 Restful API 进行通信,而您仍想使用 HttpClient,则可以使用 RestTemplate 而不是 HttpClient.
So, if the goal is to communicate with a Restful API, and you still want to use HttpClient, you can use RestTemplate over HttpClient.
请注意,我刚才所说的正是您链接到的博客所解释的:
Note that what I just said is exactly what the blog you linked to explains:
因此,解决方案是使用 org.springframework.http.client.HttpComponentsClientHttpRequestFactory,它是一个 ClientHttpRequestFactory,将请求的创建委托给 HttpClient.
这篇关于Spring项目中生产代码的RestTemplate vs Apache Http Client的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!