简介

  1. RestTemplate是spring支持的一个请求http rest服务的模板对象,性质上有点像jdbcTemplate
  2. 是Spring用于同步client端的核心类,简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果。默认情况下,RestTemplate默认依赖jdk的HTTP连接工具。当然你也可以 通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponents、Netty和OkHttp。本章讨论的就是设置RestTemplate底层使用的httpclient(org.apache.http.client.HttpClient)发送请求
  3. HttpClient可以做连接池,而发送消息的工具类可以使用RestTemplate,所以如果你的项目需要http连接池,RestTemplate+httpclient连接池是一种不错的方式,可以节省开发工作,也可以更优雅的使用。

配置

  1. maven依赖
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>

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

2. Java配置类

Spring Boot 使用RestTemplate-01-使用HttpClient-LMLPHP

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "http-pool")
@Data
public class HttpPoolProperties {

    private Integer maxTotal;
    private Integer defaultMaxPerRoute;
    private Integer connectTimeout;
    private Integer connectionRequestTimeout;
    private Integer socketTimeout;
    private Integer validateAfterInactivity;

}

Spring Boot 使用RestTemplate-01-使用HttpClient-LMLPHP

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class HttpClientRestTemplateConfig {

    @Autowired
    private HttpPoolProperties httpPoolProperties;

    @Bean("httpClientRestTemplate")
    public RestTemplate httpClientRestTemplate() {
        HttpClient httpClient = httpClient();
        ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        RestTemplate restTemplate = new RestTemplate(factory);
        // 可以添加消息转换
        //restTemplate.setMessageConverters(...);
        // 可以增加拦截器
        //restTemplate.setInterceptors(...);
        return restTemplate;
    }


    @Bean
    public HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
// 设置整个连接池最大连接数 根据自己的场景决定
connectionManager.setMaxTotal(httpPoolProperties.getMaxTotal());

// 设置每个路由(域名)最大的线程数
connectionManager.setDefaultMaxPerRoute(httpPoolProperties.getDefaultMaxPerRoute());

// 设置路由(域名)对应的最大线程数,如果设置则比setDefaultMaxPerRoute(xxx)的优先级高
//connectionManager.setMaxPerRoute(new HttpRoute(new HttpHost("v2.moon.com", 80)), 20);

// validateAfterInactivity 空闲永久连接检查间隔,这个牵扯的还比较多,
// 官方推荐使用这个来检查永久链接的可用性,而不推荐每次请求的时候才去检查
connectionManager.setValidateAfterInactivity(httpPoolProperties.getValidateAfterInactivity());

RequestConfig requestConfig = RequestConfig.custom()
        // 连接上服务器(握手成功)的时间(可以设置2000),超出抛出connect timeout
        .setConnectTimeout(httpPoolProperties.getConnectTimeout())
        // 服务器返回数据(response)的时间(可以设置3000),超过抛出read timeout
        .setSocketTimeout(httpPoolProperties.getSocketTimeout())
        // 从连接池中获取连接的超时时间,超时间未拿到可用连接,会抛出以下异常
        //org.apache.http.conn.ConnectionPoolTimeoutException:
        //Timeout waiting for connection from pool
        .setConnectionRequestTimeout(httpPoolProperties.getConnectionRequestTimeout())
        .build();

return HttpClientBuilder.create()
        .setDefaultRequestConfig(requestConfig)
        .setConnectionManager(connectionManager)
        .build();
    }
}

3.使用方法

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

@Service
public class TestService {

    @Autowired
    private RestTemplate restTemplate;

    public void startTest() throws JSONException, IOException {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("first","jinjian");
        jsonObject.put("second","aaaaaaa");

        long start = System.currentTimeMillis();
        //{1} 表示第一个占位符,也可以填写name,但是这是另一个getForEntity重载方法
        //TestResponseEntity 为自定义dto
        ResponseEntity<TestResponseEntity> entity = restTemplate.getForEntity("http://39.107.104.221/api/test/{1}", TestResponseEntity.class, 123);
        long end = System.currentTimeMillis();
        long cost = end - start;
        System.out.println("耗时:"+cost);
        RuiooResponseEntity body = entity.getBody();
        body.getData();
        body.getStatus();
        body.getMessage();
        System.out.println("响应体:"+ body);
    }
}
11-25 19:07