Spring MVC及Spring Boot项目中RestTemplate的运用

第一、RestTemplate简介
RestTemplate是Spring提供的用于访问Rest服务的客端, RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率,所以很多客户端比如Android或者第三方服务商都是使用RestTemplate请求restful服务。
第二、Spring MVC项目中RestTemplate的使用
0、pom.xml增加配置

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.0</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.9.0</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-annotations</artifactId>
	<version>2.9.0</version>
</dependency>
<!--
<dependency>
	<groupId>com.fasterxml.jackson.dataformat</groupId>
	<artifactId>jackson-dataformat-xml</artifactId>
	<version>2.9.8</version>
</dependency>
-->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.1.36</version>
</dependency>

1、使用RestTemplate之前,需要初始化其实例。创建一个工具类如下,初始化实例后,可以通过注解注入调用类中。

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
 * 初始化RestTemplate对象
 * @author shixiangcheng
 * 2021-03-09
 */
@Component
public class RestClient {
    private static RestTemplate restTemplate;
    static {
        //长连接保持60秒
        PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(60, TimeUnit.SECONDS);
        //总连接数
        pollingConnectionManager.setMaxTotal(100);
        //同路由的并发数
        pollingConnectionManager.setDefaultMaxPerRoute(100);

        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setConnectionManager(pollingConnectionManager);
        // 重试次数,默认是3次,没有开启
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
        // 保持长连接配置,需要在头添加Keep-Alive
        httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

//        RequestConfig.Builder builder = RequestConfig.custom();
//        builder.setConnectionRequestTimeout(200);
//        builder.setConnectTimeout(5000);
//        builder.setSocketTimeout(5000);
//
//        RequestConfig requestConfig = builder.build();
//        httpClientBuilder.setDefaultRequestConfig(requestConfig);

//        List
headers = new ArrayList<>(); // headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36")); // headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate")); // headers.add(new BasicHeader("Accept-Language", "zh-CN")); // headers.add(new BasicHeader("Connection", "Keep-Alive")); // // httpClientBuilder.setDefaultHeaders(headers); HttpClient httpClient = httpClientBuilder.build(); //httpClient连接配置,底层是配置RequestConfig HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); //连接超时 clientHttpRequestFactory.setConnectTimeout(5000); //数据读取超时时间,即SocketTimeout clientHttpRequestFactory.setReadTimeout(5000); //连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的 clientHttpRequestFactory.setConnectionRequestTimeout(200); //缓冲请求数据,默认值是true。通过POST或者PUT大量发送数据时,建议将此属性更改为false,以免耗尽内存。 //clientHttpRequestFactory.setBufferRequestBody(false); // 添加内容转换器 List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); // messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); // messageConverters.add(new FormHttpMessageConverter()); // messageConverters.add(new MappingJackson2XmlHttpMessageConverter()); messageConverters.add(new MappingJackson2HttpMessageConverter()); restTemplate = new RestTemplate(messageConverters); restTemplate.setRequestFactory(clientHttpRequestFactory); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); } private RestClient() { } @PostConstruct public RestTemplate getRestTemplate() { return restTemplate; } }

2.调用方部分代码如下

//0.相关导入包
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
//1.利用构造方法将RestClient通过注解注入调用方
private final RestClient restClient;
@Autowired
public GPSAdapterImpl(RestClient restClient) {
	this.restClient=restClient;
}
//2.获取当前时间戳
long timestamp=System.currentTimeMillis();
//3.将(秘钥+连接符+时间戳)进行MD5加密
String sign = DigestUtils.md5Hex(this.gpsAppKey+CommonUtils.CONNECTOR+timestamp);
//4.将验证信息放入header
HttpHeaders headers = new HttpHeaders();
headers.add("sign",sign);
headers.add("appkey",this.gpsAppKey);
headers.add("stm",String.valueOf(timestamp));
headers.add("Content-Type","application/json;charset=UTF-8");
//5.组装body体
Map<String, Object> postBody = new HashMap<String, Object>(1);
postBody.put("hasGpsPos", true);
postBody.put("deviceIdList", deviceIdList);
HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(postBody, headers);
//6.调用接口
ResponseEntity<String> result = this.restClient.getRestTemplate().postForEntity("url", requestEntity,String.class);

第三、Spring Boot项目中RestTemplate的使用
1.在Spring Boot项目中初始化RestTemplate实例如下,其它使用方式和Spring MVC项目类似。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
/**
 * RestTemplate配置类
 * @author shixiangcheng
 * 2021-03-09
 */
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return factory;
    }
}

欢迎大家积极留言交流学习心得,如有任何问题可以留言,点赞的人最美丽!

你可能感兴趣的:(Http,Spring,Boot,RestTemplate,Spring,MVC,Spring,Boot,RPC)