HttpClientUtils

package com.example.http_thread.util;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ServiceUnavailableRetryStrategy;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext; import javax.net.ssl.SSLException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException; public class HttpClientUtil {
private static PoolingHttpClientConnectionManager cm = null; static {
cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(200);//多线程调用注意配置,根据线程数设定
cm.setDefaultMaxPerRoute(300);
} public static CloseableHttpClient getHttpClient() { HttpRequestRetryHandler httpRequestRetryHandler=new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
//Date date=new Date();
System.out.println("try httpRequestRetryHandler o: " +i); if (i >= 10000) {
// Do not retry if over max retry count
return false;
}
if (e instanceof InterruptedIOException) {
// Timeout
return true;
}
if (e instanceof UnknownHostException) {
// Unknown host
return false;
}
if (e instanceof ConnectTimeoutException) {
// Connection refused
return true;
}
if (e instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(httpContext);
HttpRequest request = clientContext.getRequest();
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false; }
};
CloseableHttpClient httpClient = HttpClients.custom().setRetryHandler(httpRequestRetryHandler)
.setConnectionManager(cm)
.build();
return httpClient;
}
}

如何配置使用

@Test
void testThreads() {
String url = "*********************************";
CloseableHttpClient client = HttpClientUtil.getHttpClient();
HttpGet request = new HttpGet(url);
CloseableHttpResponse response = null;
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(20000)//数据传输过程中数据包之间间隔的最大时间
.setConnectTimeout(200000)//连接建立时间,三次握手完成时间
.setExpectContinueEnabled(true)//重点参数
.setConnectionRequestTimeout(60000)
.setStaleConnectionCheckEnabled(true)//重点参数,在请求之前校验链接是否有效
.build();
request.setConfig(requestConfig);
System.out.println("111111111111111111111111111111111111");
try {
response = client.execute(request);
System.out.println("22222222222222222222222222222222");
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
System.out.println("请求失败");
}
HttpEntity resEntity = response.getEntity();
if (resEntity == null) {
System.out.println("No Response");
}
String result = EntityUtils.toString(resEntity, "UTF-8");
} catch (Exception e) {
System.out.println("0123123312"+e.getMessage()+e.getClass());
}
finally {
if (response != null) {
try {
//此处调优重点,多线程模式下可提高性能。
EntityUtils.consume(response.getEntity());//此处高能,通过源码分析,由EntityUtils是否回收HttpEntity
response.close();
} catch (IOException e) {
System.out.println("关闭response失败:" + e);
}
}
}
}

HttpClient线程池&重试机制的更多相关文章

  1. Web中线程与IIS线程池自动回收机制

    开发Web项目后,部署到 IIS上 ,运行一直稳定,当Web程序中加入了定时任务,或者线程之类的机制后,第二天发现悲催了,定时任务并没有执行,此时重新登录一下网站,定时任务又重新执行.原来IIS默认有 ...

  2. 线程池ThreadPool及Task调度死锁分析

    近1年,偶尔发生应用系统启动时某些操作超时的问题,特别在使用4核心Surface以后.笔记本和台式机比较少遇到,服务器则基本上没有遇到过. 这些年,我写的应用都有一个习惯,就是启动时异步做很多准备工作 ...

  3. java线程池拒绝策略使用实践

    前言 线程池是开发过程中使用频率较高的一个并发组件之一,本篇会结合踩刀哥之前的实践经验来分享一下线程池拒绝策略的真实使用场景,至于线程池内部原理只会简单介绍,有需要的可以自行上网学习. 线程池工作机制 ...

  4. python小demo-01: 线程池+多进程实现cpu密集型操作

    起因: 公司有一个小项目,大概逻辑如下: 服务器A会不断向队列中push消息,消息主要内容是视频的地址,服务器B则需要不断从队列中pop消息,然后将该视频进行剪辑最终将剪辑后的视频保存到云服务器.个人 ...

  5. 踏破铁鞋无觅处,从AsyncTask学Android线程池

    android对于主线程的响应时间限制的非常严格,稍有不慎就会遇到Application Not Responding(ANR)的弹框.用户可以轻点手指关掉你的APP.官方文档写的非常明确!同时,保持 ...

  6. Java并发编程中线程池源码分析及使用

    当Java处理高并发的时候,线程数量特别的多的时候,而且每个线程都是执行很短的时间就结束了,频繁创建线程和销毁线程需要占用很多系统的资源和时间,会降低系统的工作效率. 参考http://www.cnb ...

  7. JAVA线程池调优

        在JAVA中,线程可以使用定制的代码来管理,应用也可以利用线程池.在使用线程池时,有一个因素非常关键:调节线程池的大小对获得最好的性能至关重要.线程池的性能会随线程池大小这一基本选择而有所不同 ...

  8. 线程池 API (转)

    文档原始地址    目录 线程池概述 线程池对象 回调环境对象 工作对象 等待对象 计时器对象 I/O 完成对象 使用清理组简化清理 回调实例 API    随着 Windows Vista® 的发布 ...

  9. 当ThreadLocal碰上线程池

    ThreadLocal使用 ThreadLocal可以让线程拥有本地变量,在web环境中,为了方便代码解耦,我们通常用它来保存上下文信息,然后用一个util类提供访问入口,从controller层到s ...

  10. java线程池,阿里为什么不允许使用Executors?

    带着问题 阿里Java代码规范为什么不允许使用Executors快速创建线程池? 下面的代码输出是什么? ThreadPoolExecutor executor = new ThreadPoolExe ...

随机推荐

  1. [Leetcode]完全平方数

    题目 代码 class Solution { public: int numSquares(int n) { vector<int> dp(n + 1, INT_MAX); dp[0] = ...

  2. [Leetcode]反转字符串中的单词 III

    题目 代码 class Solution { public: string reverseWords(string s) { for(int i=0,j=0;j<=s.size();j++) { ...

  3. Ubuntu 22.04 运行 Appimage 文件

    解决方法 sudo apt-get update sudo apt install fuse libfuse2 chmod a+x *.appimage 参考资料 https://bynss.com/ ...

  4. Objects非空判断-声明异常throws

    Objects非空判断 还记得我们学习过一个类Objects吗,曾经提到过它由一些静态的实用方法组成,这些方法是null-save(空指针安全的)或null-tolerant (容忍空指针的),那么在 ...

  5. 一文讲尽Thread类的源码精髓

    摘要:今天,我们就一起来简单看看Thread类的源码. 本文分享自华为云社区<[高并发]Thread类的源码精髓>,作者:冰 河. 前言 最近和一个朋友聊天,他跟我说起了他去XXX公司面试 ...

  6. MyBatis使用四(查询详解)

    本文主要讲述如何在mybatis中进行查询操作[详解] 一. 查询User对象 1.查询单个对象User SelectUser接口声明如下 // 主要条件是使用id public interface ...

  7. Grafana 系列文章(十五):Exemplars

    Exemplars 简介 Exemplar 是用一个特定的 trace,代表在给定时间间隔内的度量.Metrics 擅长给你一个系统的综合视图,而 traces 给你一个单一请求的细粒度视图:Exem ...

  8. Linux10-rpm和yum

    1.rpm包的管理 一种用于互联网下载包的打包及安装工具,它包含在某些Linux分发版中.它生成具有.RPM扩展名的文件.RPM是RedHat Package Manager(RedHat软件包管理工 ...

  9. C#支付宝用户的静默授权

    支付宝官方的用户信息授权,具体地址:https://opendocs.alipay.com/open/289/105656 商户/开发者通过以下的 URL 拼接规则拼接用户授权的 URL 地址,该地址 ...

  10. Python学习常见问题及其解决方案(1)

    1.ModuleNotFoundError: No module named 'urllib2' 解决方案: 1)https://blog.csdn.net/weixin_45598506/artic ...