HttpClient4.5X使用-集成微服务
HttpClient4.5X使用-集成微服务
1.什么是HttpClient
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。现在HttpClient最新版本为 HttpClient 4.5 .6(官网)
实际应用中我们通常使用在复杂soap协议类型的调用。Springboot一般推荐有RestTemplate 。
2. 整合 HttpClient
1.配置类,主要配置httpClient 连接池的信息
@ConfigurationProperties(prefix = HttpClientProperties.PREFIX)
public class HttpClientProperties {
public static final String PREFIX = "http.config"; //默认连接池最大连接数
private Integer httpMaxTotal = 300; //默认整个连接池默认最大连接数
private Integer httpDefaultMaxPerRoute = 100; //设置请求超时 默认30s
private Integer httpConnectTimeout = 30 * 1000; //设置请求响应超时时间 默认5min
private Integer getHttpReadTimeout = 5 * 60 * 1000; //设置从连接池获取中获取到连接最长时间
private Integer httpConnectionRequestTimeout = 500; //设置数据传输的最长时间
private Integer httpSocketTimeout = 5 * 60 * 1000; //设置默认请求类型http 、https
private String hostType ="http"; public Integer getHttpMaxTotal() {
return httpMaxTotal;
} public void setHttpMaxTotal(Integer httpMaxTotal) {
this.httpMaxTotal = httpMaxTotal;
} public Integer getHttpDefaultMaxPerRoute() {
return httpDefaultMaxPerRoute;
} public void setHttpDefaultMaxPerRoute(Integer httpDefaultMaxPerRoute) {
this.httpDefaultMaxPerRoute = httpDefaultMaxPerRoute;
} public Integer getHttpConnectTimeout() {
return httpConnectTimeout;
} public void setHttpConnectTimeout(Integer httpConnectTimeout) {
this.httpConnectTimeout = httpConnectTimeout;
} public Integer getGetHttpReadTimeout() {
return getHttpReadTimeout;
} public void setGetHttpReadTimeout(Integer getHttpReadTimeout) {
this.getHttpReadTimeout = getHttpReadTimeout;
} public Integer getHttpConnectionRequestTimeout() {
return httpConnectionRequestTimeout;
} public void setHttpConnectionRequestTimeout(Integer httpConnectionRequestTimeout) {
this.httpConnectionRequestTimeout = httpConnectionRequestTimeout;
} public Integer getHttpSocketTimeout() {
return httpSocketTimeout;
} public void setHttpSocketTimeout(Integer httpSocketTimeout) {
this.httpSocketTimeout = httpSocketTimeout;
} public String getHostType() {
return hostType;
} public void setHostType(String hostType) {
this.hostType = hostType;
}
}
2.初始化连接池信息
@Configuration
@ConditionalOnClass(HttpClientConfig.class)
@EnableConfigurationProperties(HttpClientProperties.class)
public class HttpClientConfig { @Autowired
HttpClientProperties httpClientProperties;
@Autowired
private PoolingHttpClientConnectionManager manager; @Bean
public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
// 最大连接数
poolingHttpClientConnectionManager.setMaxTotal(httpClientProperties.getHttpMaxTotal());
// 每个主机的最大并发数
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpClientProperties.getHttpDefaultMaxPerRoute());
return poolingHttpClientConnectionManager;
} @Bean
public IdleConnectionEvictor idleConnectionEvictor(PoolingHttpClientConnectionManager poolingHttpClientConnectionManager ) {
// 定期清理无效连接
return new IdleConnectionEvictor(poolingHttpClientConnectionManager, 1L, TimeUnit.HOURS);
} @Bean
public RequestConfig requestConfig() {
// 请求配置
// 创建连接的最长时间
return RequestConfig.custom().setConnectTimeout(httpClientProperties.getHttpConnectTimeout())
// 从连接池中获取到连接的最长时间
.setConnectionRequestTimeout(httpClientProperties.getHttpConnectTimeout())
// 数据传输的最长时间
.setSocketTimeout(httpClientProperties.getHttpSocketTimeout())
.build();
} /**
* 通过httpClients直接获取
* @param requestConfig 配置信息
* @return
*/
@Bean
@Scope("prototype") //此处是多例模式,因为考虑连接池使用都会手动关闭,同时单例会存在未知问题
public CloseableHttpClient closeableHttpClient(RequestConfig requestConfig) {
return HttpClients.custom().setConnectionManager(this.manager).setDefaultRequestConfig(requestConfig).build();
} /**
* 通过HttpClientBuilder 间接获取
* @param requestConfig 配置信息
* @return
*/
@Bean
public HttpClientBuilder httpClientBuilder(PoolingHttpClientConnectionManager poolingHttpClientConnectionManager, RequestConfig requestConfig){
return HttpClientBuilder.create().setConnectionManager(poolingHttpClientConnectionManager).setDefaultRequestConfig(requestConfig);
} }
3.httpclientUtil
@Component
public class HttpClientUtil { @Autowired
private CloseableHttpClient httpClient; /**
* get请求用于普通接口调用
*
* @param url 请求地址
* @param headers 请求头
* @param params 参数
* @return
* @throws Exception
*/
public String doGet(String url,
Map<String, String> headers,
Map<String, String> params) {
// //创建一个默认可关闭的httpclient对象
// CloseableHttpClient httpClient = HttpClients.createDefault();
//定义httpResponse 对象
CloseableHttpResponse response = null;
//反馈信息
String resultMsg = null;
try {
//设置请求地址
URIBuilder builder = new URIBuilder(url);
//拼接地址
if (!CollectionUtils.isEmpty(params)) {
params.forEach((k, v) -> {
builder.addParameter(k, v);
});
}
//设置请求头
HttpGet httpGet = new HttpGet(builder.build());
if (!CollectionUtils.isEmpty(headers)) {
headers.entrySet().stream().map(e -> {
httpGet.addHeader(e.getKey(), e.getValue());
return httpGet;
});
}
// 执行请求
response = httpClient.execute(httpGet);
// 判断返回状态为200则给返回值赋值
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//构造反馈
resultMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
//构造反馈SRM
e.printStackTrace();
} finally {
//连接池关闭
httpClientCloseResponse(httpClient, response);
}
return resultMsg;
} /**
* 无请求体post请求 post form
*
* @param url 请求地址
* @param headers 请求头
* @param params 参数
* @return
* @throws Exception
*/
public String doPost(String url,
Map<String, String> headers,
Map<String, String> params) {
//创建一个默认可关闭的httpclient对象
// CloseableHttpClient httpClient = HttpClients.createDefault();
//定义httpResponse 对象
CloseableHttpResponse response = null;
//反馈信息
String resultMsg = null;
try {
//设置请求地址
URIBuilder builder = new URIBuilder(url);
//拼接地址
if (!CollectionUtils.isEmpty(params)) {
params.forEach((k, v) -> {
builder.addParameter(k, v);
});
}
//设置请求头
HttpPost httpPost = new HttpPost(builder.build());
if (!CollectionUtils.isEmpty(headers)) {
headers.forEach((k, v) -> {
httpPost.addHeader(k, v);
});
}
// 执行请求
response = httpClient.execute(httpPost);
// 判断返回状态为200则给返回值赋值
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//构造反馈
resultMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
//构造反馈SRM
e.printStackTrace();
} finally {
//连接池关闭
httpClientCloseResponse(httpClient, response);
}
return resultMsg;
} /**
* 请求体post请求 post
*
* @param url 请求地址
* @param headers 请求头
* @param params 参数信息
* @param body 请求体
* @return 反馈结果
* @throws Exception
*/
public String doPost(String url,
Map<String, String> headers,
Map<String, String> params,
String body) {
//创建一个默认可关闭的httpclient对象
// CloseableHttpClient httpClient = HttpClients.createDefault();
//定义httpResponse 对象
CloseableHttpResponse response = null;
//反馈信息
String resultMsg = null;
try {
//设置请求地址
URIBuilder builder = new URIBuilder(url);
//拼接地址
if (!CollectionUtils.isEmpty(params)) {
List<NameValuePair> nameValuePairs = params.entrySet().stream().map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue())).collect(Collectors.toList());
builder.setParameters(nameValuePairs);
}
//设置请求头
HttpPost httpPost = new HttpPost(builder.build());
if (!CollectionUtils.isEmpty(headers)) {
headers.forEach((k, v) -> {
httpPost.addHeader(k, v);
});
}
//设置请求体
if (StringUtils.isNotBlank(body)) {
httpPost.setEntity(new StringEntity(body, "utf-8"));
}
// 执行请求
response = httpClient.execute(httpPost);
// 判断返回状态为200则给返回值赋值
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//构造反馈
resultMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
//构造反馈SRM
e.printStackTrace();
} finally {
//连接池关闭
httpClientCloseResponse(httpClient, response);
}
return resultMsg; } /**
* 构建请求的 url
*
* @param uri
* @param querys
* @return
* @throws UnsupportedEncodingException
*/
private String buildUrl(String uri, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(uri);
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
} /**
* 将结果转换成JSONObject
*
* @param httpResponse
* @return
* @throws IOException
*/
public JSONObject getJson(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
String resp = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return JSON.parseObject(resp);
} /**
* 关闭连接池反馈
*
* @param httpResponse
*/
public void httpClientCloseResponse(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) {
try {
if (httpResponse != null) {
httpResponse.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
} }
3.为什么使用HttpClient并且使用连接池
日常调用时候我们经常碰见这样的问题:
Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
at sun.security.ssl.Handshaker.processLoop(Unknown Source)
at sun.security.ssl.Handshaker.process_record(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)
at com.hx.net.Test3.main(Test3.java:21)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.validate(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 12 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(Unknown Source)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
... 18 more
证书认证问题SSL,网上处理方式参差不齐。因此通过 查看PoolingHttpClientConnectionManager实例化源码我们发现
private static Registry<ConnectionSocketFactory> getDefaultRegistry() {
return RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
}
public PoolingHttpClientConnectionManager() {
this(getDefaultRegistry());
}
httpclient 连接池已经对ssl证书初始化注册是有非常良好的集成。
HttpClient4.5X使用-集成微服务的更多相关文章
- 开源:Taurus.MVC-Java 版本框架 (支持javax.servlet.*和jakarta.servlet.*双系列,内集成微服务客户端)
版本说明: 因为之前有了Taurus.MVC-DotNet 版本框架,因此框架标了-Java后缀. .Net 版本: 开源文章:开源:Taurus.MVC-DotNet 版本框架 (支持.NET C ...
- Taurus.MVC 微服务框架 入门开发教程:项目集成:2、客户端:ASP.NET Core(C#)项目集成:应用中心。
系列目录: 本系列分为项目集成.项目部署.架构演进三个方向,后续会根据情况调整文章目录. 本系列第一篇:Taurus.MVC V3.0.3 微服务开源框架发布:让.NET 架构在大并发的演进过程更简单 ...
- Taurus.MVC 微服务框架 入门开发教程:项目集成:3、客户端:其它编程语言项目集成:Java集成应用中心。
系列目录: 本系列分为项目集成.项目部署.架构演进三个方向,后续会根据情况调整文章目录. 开源地址:https://github.com/cyq1162/Taurus.MVC 本系列第一篇:Tauru ...
- Chris Richardson微服务翻译:重构单体服务为微服务
Chris Richardson 微服务系列翻译全7篇链接: 微服务介绍 构建微服务之使用API网关 构建微服务之微服务架构的进程通讯 微服务架构中的服务发现 微服务之事件驱动的数据管理 微服务部署 ...
- 微服务和SpringCloud入门
微服务和SpringCloud入门 微服务是什么 微服务的核心是将传统的一站式应用,根据业务拆分成一个一个的服务,彻底去耦合,每个微服务提供单个业务功能的服务,一个服务做一件事情,从技术角度看就是一种 ...
- 推荐一款 Python 微服务框架 - Nameko
1. 前言 大家好,我是安果! 考虑到 Python 性能及效率性,Python Web 端一直不温不火,JAVA 和 Golang 的微服务生态一直很繁荣,也被广泛用于企业级应用开发当中 本篇文章 ...
- 架构师成长之路也该了解的新一代微服务技术-ServiceMesh(上)
架构演进 发展历程 我们再来回顾一下架构发展历程,从前往后的顺序依次为单机小型机->垂直拆分->集群化负载均衡->服务化改造架构->服务治理->微服务时代 单机小型机:采 ...
- NET Core微服务之路:自己动手实现Rpc服务框架,基于DotEasy.Rpc服务框架的介绍和集成
本篇内容属于非实用性(拿来即用)介绍,如对框架设计没兴趣的朋友,请略过. 快一个月没有写博文了,最近忙着两件事; 一:阅读刘墉先生的<说话的魅力>,以一种微妙的,你我大家都会经常遇见 ...
- 【下一代核心技术DevOps】:(五)微服务CI与Rancher持续集成
1. 引言 DevOps的核心魅力是快速的持续集成交付,降低研发和实施运维之间的交互,使得传统的各种扯皮现象统统消失.最重要的是降低成本 保障产品交付可靠性. 使用Rancher作为持续集成的关键环节 ...
随机推荐
- rabbitmq之后台管理和用户设置
前言 前面介绍了erlang环境的安装和rabbitmq环境安装,接下来介绍rabbitmq的web管理和用户设置. 启用后台管理插件 通过后台管理插件我们可以动态监控mq的流量,创建用户,队列等. ...
- virtualbox 网络地址转换(NAT)
网络地址转换 虚拟机可以访问主机 通过主机请求外网 但是主机不能请求虚拟机 所以要配置端口转发才行 host-only模式下 不同网段的不同虚拟机也可以互相ping通 比如 192.168.33.1 ...
- wifi - 无线相关命令
1.Linux环境下的无线相关操作命令 interface 指代当前网卡 一般是 wifi0 , eth0 , ath1等 ifconfig - 常用查看网络设定及控制网卡(Windows下是ip ...
- 完美解决pyinstaller 打包报错找不到依赖pypiwin32 或pywin32-ctypes的错误
报错信息 最近闲来无事,用python的tkinter库开发了一款带日程提醒的万年历桌面程序.在程序开发结束开始打包时,却发现一直报错 PyInstaller cannot check for ass ...
- Anderson《空气动力学基础》5th读书笔记导航
没错,在2018年,我正式启程了安德森教授这本空气动力学圣经的阅读,为了深入理解概念,特写此刊,边读边写,2020年一定写完,写不完我就/¥@%¥---! 以下是导航: 第一章任务图: 第一章思维导图 ...
- CSS实现鼠标移入弹出下拉框
前言 最近比较沉迷CSS,所以我现在来做个鼠标的交互效果 HTML <ul> <li>测试</li> <li>测试</li> <li ...
- Java POST请求案例
<<<<<<<<<<<<<<<<<<<<<<<<< ...
- 变量分割技术、判别学习(discriminative learning method)
基于模型的优化方法(model-based optimization method): 小波变换.卡尔曼滤波.中值滤波.均值滤波: 优点:对于处理不同的逆问题都非常灵活:缺点:为了更好的效果而采用各种 ...
- 浅谈分布式共识算法raft
前言:在分布式的系统中,存在很多的节点,节点之间如何进行协作运行.高效流转.主节点挂了怎么办.如何选主.各节点之间如何保持一致,这都是不可不面对的问题,此时raft算法应运而生,专门 用来解决上述问题 ...
- leo101
tags: 贪心 date: 2019-4-4 jag2017autumnJ Farm Village 题面 题目链接 翻译 数轴上有 n 个村庄,每个村庄可以生产两个单位的粮食.在每个村庄生产一单位 ...