RestTemplate的几种实现

RestTemplate的几种实现

2018年08月25日 23:47:58 月未明 阅读数:4300
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35981283/article/details/82056285
环境

Spring Boot2.0
JDK 1.8
RestTemplate是spring的一个rest客户端,在spring-web这个包下,spring boot的依赖如下

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

点进去可以看到spring-web

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>5.0.4.RELEASE</version>
  <scope>compile</scope>
</dependency>

所以如果在非spring的框架下直接引入spring-web这个包即可。

RestTemplate只是对其它Rest客户端的一个封装,本身并没有自己的实现。
很多人都说Spring Boot 2.0之前RestTestTemplate的默认实现是HttpClient,2.+为OKHttp3,其实这种说法并不完全正确,如果没有引入这些客户端的jar包,其默认实现是HttpURLConnection(集成了URLConnection),这是JDK自带的REST客户端实现。

RestTemplate有三个实现

  1. RestTemplate()
  2. RestTemplate(List<HttpMessageConverter<?>> messageConverters)
  3. RestTemplate(ClientHttpRequestFactory requestFactory)。

RestTemplate(ClientHttpRequestFactory requestFactory)是为们要说的重点,跟踪ClientHttpRequestFactory查看其实现,如下图

这里写图片描述

先看默认实现的测试代码

RestConfig

package com.pk.client.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * Created by pangkunkun on 2018/8/25.
 */
@Configuration
public class RestConfig {
    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate;
    }
}

MyRestController

package com.pk.client.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by pangkunkun on 2018/8/25.
 */
@RestController
public class MyRestController {

    private static final Logger logger = LoggerFactory.getLogger(MyRestController.class);

    @Autowired
    private RestTemplate restTemplate;

    private static final String URL = "http://localhost:8081/server";

    @GetMapping("/default")
    public void defaultRestClient(){
        String result = restTemplate.getForObject(URL,String.class);
        logger.info("result = {}",result);
    }

}

Server端代码

package com.pk.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by pangkunkun on 2018/8/25.
 */
@SpringBootApplication
@RestController
public class RestServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestServerApplication.class,args);
    }

    @GetMapping("/server")
    public String restServer(){
        System.out.println("This is rest server");
        return "success";
    }
}

在浏览器调用client之后会追踪到下面这里
这里写图片描述
在这里就可以看到其实现方式是HttpURLConnection(URLConnection)。
所以,在没有第三方依赖的情况下其默认实现是URLConnection。

现在来看下其它几种客户端的引入。在ClientHttpRequestFactory的实现那张图中列出了RestTemplate的几种REST Client的封装。其中最常用的有以下三种:

SimpleClientHttpRequestFactory(封装URLConnection)
HttpComponentsClientHttpRequestFactory(封装HttpClient)
OkHttp3ClientHttpRequestFactory(封装OKHttp)
其实Netty4ClientHttpRequestFactory这个为在测试的时候也测试过,不过spring boot 2.0之后就不推荐使用了,而且我测试的时候性能上明显不如其它几个,所以这里没加上
其切换与使用也很简单,在pom中引入相应依赖

  <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.11.0</version>
        </dependency>
    </dependencies>

在Config中的配置

package com.pk.client.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * Created by pangkunkun on 2018/8/25.
 */
@Configuration
public class RestConfig {

    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate;
    }

    @Bean("urlConnection")
    public RestTemplate urlConnectionRestTemplate(){
        RestTemplate restTemplate = new RestTemplate(new SimpleClientHttpRequestFactory());
        return restTemplate;
    }

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

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

其实使用的时候一般都会只选择其中的一种,所以上面的几种配置任选其一,替换掉最上边那个就好。其它不再细说了。
这里是代码的GitHub地址RestTemplateSample。

https://github.com/rhettpang/RestTemplateSample

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值