RestTemplate做转发(httpclient作为请求体封装类)

本文档详细介绍了如何使用RestTemplate进行HTTP请求转发,包括引入依赖、配置RestTemplate、创建发送请求的工具类,特别是针对POST请求中ServletInputStream的读取配置,并讲解了如何重写RestTemplate的响应内容解析类以满足多次读取的需求。
摘要由CSDN通过智能技术生成

目录

引入依赖包

RestTemplate配置类

发送请求的工具类 

 POST请求,对ServletInputStream的读取配置

RestTemplate请求返回内容解析类重写


引入依赖包

		<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>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

 

RestTemplate配置类

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Configuration
public class RestTemplateConfig {
    @Resource
    private CustomHttpMessageConverter customHttpMessageConverter;
    /**
     * 初探RestTemplate--解决中文乱码问题
     * https://blog.csdn.net/mryang125/article/details/80963280
     * @return
     */
    @Bean
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory factory = httpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(factory);
        // 可以添加消息转换 restTemplate.setMessageConverters(...);
        restTemplate.getMessageConverters().set(5,customHttpMessageConverter);//解决请求返回数据restTemplate内部解析数据异常
        restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        // 可以增加拦截器
        //restTemplate.setInterceptors(...);
        //解决中文乱码问题
        List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
        for (HttpMessageConverter<?> httpMessageConverter : list) {
            if(httpMessageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(StandardCharsets.UTF_8);
                break;
            }
        }
        return restTemplate;
    }
    private HttpComponentsClientHttpRequestFactory  httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(restTemplateConfigHttpClient());
    }
    private HttpClient restTemplateConfigHttpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        // 设置整个连接池最大连接数 根据自己的场景决定
        connectionManager.setMaxTotal(200);
        // 路由是对maxTotal的细分
        connectionManager.setDefaultMaxPerRoute(50);
        RequestConfig requestConfig = RequestConfig.custom()
                // 服务器返回数据(response)的时间,超过该时间抛出read timeout
                .setSocketTimeout(30000)
                // 连接上服务器(握手成功)的时间,超出该时间抛出connect timeout
                .setConnectTimeout(5000)
               
异步RestTemplate是Spring提供的一种并发处理能力较强的HttpClient,它能够在发送HTTP请求时自动创建新的线程池,充分发挥多CPU核心下的并行处理能力。在处理高并发请求时,异步RestTemplate的效率远高于同步方式。 在使用异步RestTemplate实现HTTP异步请求通用Utils时,我们可以定义一个静态方法,该方法接收URL、请求方式、请求参数和回调函数等参数,将这些参数封装成RequestEntity对象,并使用异步RestTemplate进行异步HTTP请求。 具实现方式如下: 1. 引入异步RestTemplate依赖,如下所示: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 定义异步HTTP请求通用Utils,如下所示: ``` @Component public class HttpUtils { private final AsyncRestTemplate asyncRestTemplate; public HttpUtils(AsyncRestTemplate asyncRestTemplate) { this.asyncRestTemplate = asyncRestTemplate; } public static void asyncRequest(String url, HttpMethod method, HttpHeaders headers, Object requestBody, ParameterizedTypeReference responseType, AsyncCallback callback) { RequestEntity request = new RequestEntity(requestBody, headers, method, URI.create(url)); ListenableFuture<ResponseEntity> future = asyncRestTemplate.exchange(request, responseType); future.addCallback(callback); } } ``` 3. 在需要进行异步HTTP请求的位置调用HttpUtils的asyncRequest方法即可,如下所示: ``` HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); JSONObject requestBody = new JSONObject(); requestBody.put("username", "admin"); requestBody.put("password", "123456"); ParameterizedTypeReference responseType = new ParameterizedTypeReference<ApiResponse<Object>>() {}; HttpUtils.asyncRequest("http://localhost:8080/login", HttpMethod.POST, headers, requestBody, responseType, new AsyncCallback() { @Override public void onSuccess(ResponseEntity responseEntity) { ApiResponse<Object> response = responseEntity.getBody(); System.out.println(response); } @Override public void onFailure(Throwable throwable) { throwable.printStackTrace(); } }); ``` 以上就是使用异步RestTemplate实现HTTP异步请求通用Utils的步骤和详细说明。通过封装通用的异步HTTP请求方法,我们可以在各个业务模块中灵活调用,提高代码的复用性和可读性,同时也能够快速地响应请求,提高系统的并发处理能力。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值