雪花新闻

精讲RestTemplate第2篇-多种底层HTTP客户端类库的切换

本文是精讲RestTemplate第2篇,前篇的blog访问地址如下:

RestTemplate只是对其他的HTTP客户端的封装,其本身并没有实现HTTP相关的基础功能。其底层实现是可以配置切换的,我们本小节就带着大家来看一下RestTemplate底层实现,及如何实现底层基础HTTP库的切换。

一、源码分析

RestTemplate有一个非常重要的类叫做HttpAccessor,可以理解为用于HTTP接触访问的基础类。下图为源码:

从源码中我们可以分析出以下几点信息

二、底层实现切换方法

从开发人员的反馈,和网上的各种HTTP客户端性能以及易用程度评测来看,OkHttp 优于 Apache HttpComponents、Apache HttpComponents优于HttpURLConnection。所以我个人更建议大家将底层HTTP实现切换为okHTTP。

以下所讲的切换方法,基于第一篇内容: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用

2.1.切换为okHTTP

首先通过maven坐标将okHTTP的包引入到项目中来

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.7.2</version>
</dependency>

如果是spring 环境下通过如下方式使用OkHttp3ClientHttpRequestFactory初始化RestTemplate bean对象。

@Configuration
public class ContextConfig {
    @Bean("OKHttp3")
    public RestTemplate OKHttp3RestTemplate(){
        RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());
        return restTemplate;
    }
}

如果是非Spring环境,直接 new RestTemplate(new OkHttp3ClientHttpRequestFactory() 之后使用就可以了。

2.2.切换为Apache HttpComponents

与切换为okHTTP方法类似、不再赘述。

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

使用HttpComponentsClientHttpRequestFactory初始化RestTemplate bean对象

@Bean("httpClient")
public RestTemplate httpClientRestTemplate(){
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    return restTemplate;
}

欢迎关注我的博客,里面有很多精品合集

觉得对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创作动力!。另外,笔者最近一段时间输出了如下的精品内容,期待您的关注。

相关文章