Spring中的RestTemplate类源自spring-web,http调用中设置超时时间、设置连接池管理等非常重要,保证了系统的可用性,避免了长时间连接不上或者等待数据返回,拖垮系统。

现贴出工作上关于RestTemplate的标准配置,设置了超时时间、连接池等,开箱即用。

package com.pab.bloan.charge.app.common.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
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.http.converter.HttpMessageConverter;
import org.springframework.web.client.RestTemplate; import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit; @Configuration
public class RestTemplateConfig { private static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 100; private static final int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 10; private static final int DEFAULT_MAX_TIME_OUT = 3000; @Value("${rest-template.timeout:3000}")
private int defaultTimeOut; @Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
List<HttpMessageConverter<?>> converters = new ArrayList<>();
FastJsonHttpMessageConverter jacksonMessageConverter = new FastJsonHttpMessageConverter();
converters.add(jacksonMessageConverter);
restTemplate.setMessageConverters(converters);
return restTemplate;
} @Bean
public ClientHttpRequestFactory httpRequestFactory() {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
RequestConfig requestConfig = RequestConfig.custom()
// 连接超时
.setConnectTimeout(defaultTimeOut)
// 排队超时
.setConnectionRequestTimeout(defaultTimeOut)
// 数据读取超时
.setSocketTimeout(defaultTimeOut)
.build();
requestFactory.setConnectTimeout(defaultTimeOut);
requestFactory.setReadTimeout(defaultTimeOut);
SocketConfig socketConfig = SocketConfig
.custom()
.setSoKeepAlive(false)
.setTcpNoDelay(true)
.build();
PoolingHttpClientConnectionManager pm = new PoolingHttpClientConnectionManager();
pm.setDefaultSocketConfig(socketConfig);
pm.closeIdleConnections(DEFAULT_MAX_TIME_OUT, TimeUnit.MICROSECONDS);
pm.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
pm.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(pm)
.build();
requestFactory.setHttpClient(httpClient);
return requestFactory;
}
}

使用示例(代码中将相关的请求url、请求参数、响应参数,替换掉即可):

/**
* 调用渠道查询客户经理名单接口
* @param saleManagerRequest
* @return
*/
private SaleManagerResponse requestQDSaleManagerApi(SaleManagerRequest saleManagerRequest) {
// 调用外联额度变更接口
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<SaleManagerResponse> responseEntity =
restTemplate.postForEntity(accessGatewayService.getAccessGatewayRequestUrl(qdSaleManagerSearchUrl),
new HttpEntity<>(saleManagerRequest, headers), SaleManagerResponse.class); if (responseEntity.getStatusCode() == HttpStatus.OK) {
SaleManagerResponse saleManagerResponse = responseEntity.getBody();
if (saleManagerResponse != null
&& Response.SUCCESS.equals(saleManagerResponse.getResponseCode())) {
return saleManagerResponse;
} else {
log.error("request destination error:[requestUrl:{}; request:{}; response:{}]",
new Object[]{qdSaleManagerSearchUrl, saleManagerRequest, saleManagerResponse});
throw new BusinessException("调用渠道查询客户经理名单接口异常");
}
} else {
throw new BusinessException("调用渠道查询客户经理名单接口网络不可达");
}
}

标准化代码,用起来美滋滋。

Spring中RestTemplate进行Http调用的更多相关文章

  1. 不使用SpringBoot如何将原生Feign集成到Spring中来简化http调用

    在微服务架构中,如果使用得是SpringCloud,那么只需要集成SpringFeign就可以了,SpringFeign可以很友好的帮我们进行服务请求,对象解析等工作. 然而SpingCloud是依赖 ...

  2. Spring中RestTemplate的使用方法

    一.REST 在互联网中,我们会通过请求url来对网络上的资源做增删改查等动作,这里的请求包含两部分:动词,主要包括增.删.改.查:名词,就是网络中的各种资源.传统的非REST风格的请求方式是把动词和 ...

  3. 使用Spring的RestTemplate进行接口调用

    引自:http://www.zimug.com/ 1.常见的http服务的通信方式 经常使用的方式有HttpClient.OkHttp.RestTemplate.其中RestTemplate是一种更优 ...

  4. Spring中利用applicationContext.xml文件实例化对象和调用方法

    Spring中实例化对象和调用方法入门 1.jar包和xml的准备 已上传至百度云盘,链接: https://pan.baidu.com/s/1CY0xQq3GLK06iX7tVLnp3Q 提取码: ...

  5. c3p0在spring中的配置

    在大家的开发和学习其中应该经经常使用到数据库的连接和使用,只是连接 的方式就有非常多种方式了,例如说用最最简单的JDBC 也好,还实用比 较复杂一点的就是数据库连接池.当然还有使用DBCP的连接的,各 ...

  6. 【Spring】Spring中的Bean - 4、Bean的生命周期

    Bean的生命周期 简单记录-Java EE企业级应用开发教程(Spring+Spring MVC+MyBatis)-Spring中的Bean 了解Spring中Bean的生命周期有何意义? 了解Sp ...

  7. JAVA微服务应用(1)--SpringBoot中的REST API调用(学习笔记)

    好长时间没有写学习小结了,最近宁正好看了小马哥的微服务系列之<Spring Boot>系列,颇有收获,并且公司也布置一个课题就是关于Spring中的REST API调用.于是乎回归本行,再 ...

  8. spring boot2X整合Consul一使用RestTemplate实现服务调用

    Consul可以用于实现分布式系统的服务发现与配置 服务调用有两种方式: A.使用RestTemplate 进行服务调用 负载均衡——通过Ribbon注解RestTemplate B.使用Feign ...

  9. 分析spring事务@Transactional注解在同一个类中的方法之间调用不生效的原因及解决方案

    问题: 在Spring管理的项目中,方法A使用了Transactional注解,试图实现事务性.但当同一个class中的方法B调用方法A时,会发现方法A中的异常不再导致回滚,也即事务失效了. 当这个方 ...

随机推荐

  1. 浏览器端js处理or直接冗余至服务器php处理?

    w交给客户端浏览器js处理,减少向服务器的提交字节.精简处理逻辑.

  2. Exception in thread "main" java.lang.UnsupportedClassVersionError: * : Unsupported major.minor version 52.0 解决办法

    Exception in thread "main" java.lang.UnsupportedClassVersionError: * : Unsupported major.m ...

  3. Apache 2.4 配置多个虚拟主机的问题

    以前一直用Apache2.2的版本,最近升级到了2.4的版本,尝尝新版本嘛. 不过遇到了几个问题,一个就是配置了多个virtualhost,虽然没有报错,不过除了第一可以正常访问外,其他的都存在403 ...

  4. requests和bs4

    requests模块,仿造浏览器发送Http请求bs4主要对html或xml格式字符串解析成对象,使用find/find_all查找 text/attrs 爬取汽车之家 爬取汽车之家的资讯信息,它没有 ...

  5. 前端开发 - jsBom

    一.jsBom简介 jsBom = javascript browser object modelBOM指的是浏览器对象模型 Browser Object Model,它的核心就是浏览器. 二.Bom ...

  6. Python并行编程(八):with语法

    1.基本概念 当有两个相关的操作需要在一部分代码块前后分别执行的时候,可以使用with语法自动完成.同时,使用with语法可以在特定的地方分配和释放资源,因此,with语法也叫作"上下文管理 ...

  7. git在使用中出现 refusing to merge unrelated histories如何解决?

    一.GIT的使用 # 设置用户名 git config --global user.name "zhaijihai" # 设置用户邮箱 git config --global us ...

  8. git学习------> Gitlab如何进行备份恢复与迁移?

    前段时间,在某台CenterOS服务器上搭建了Gitlab环境,并且大家陆陆续续的都把代码从svn迁移到了gitlab,但是之前的CenterOS服务器并不是搭建在公司的机房环境,而是搭建在办公室的某 ...

  9. Spring源码解析(一)开篇

    前言 Spring源码继承结构比较复杂,看过以后经常会忘记.因此,记录一下源码分析的过程,方便以后回顾.本次分析的Spring源码版本为3.2.15. 另外,一提Spring就是IOC.DI等等,我们 ...

  10. 详解Spark sql用户自定义函数:UDF与UDAF

    UDAF = USER DEFINED AGGREGATION FUNCTION Spark sql提供了丰富的内置函数供猿友们使用,辣为何还要用户自定义函数呢?实际的业务场景可能很复杂,内置函数ho ...