HttpUtils带连接池
准备祖传了,有问题欢迎大家指正。
HttpUtil
import com.txlc.cloud.commons.exception.ServiceException;
import com.txlc.dwh.common.constants.MyErrorCode;
import org.ssssssss.script.annotation.Comment;import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;/*** @author **/
public class HttpUtil {public static final String UTF_8 = "UTF-8";private static final PooledHttpClientAdaptor adaptor = new PooledHttpClientAdaptor();@Comment("http get")public static String doGet(@Comment("url")String apiUrl, @Comment("请求头,没有请传null")Map<String, String> headers, @Comment("url参数")Map<String, Object> params) {return adaptor.doGet(apiUrl, headers, params);}public static String doFormPost(@Comment("url")String apiUrl, @Comment("请求头,没有请传null")Map<String, String> headers, @Comment("form参数")Map<String, Object> params) {return adaptor.doPost(apiUrl, headers, params);}public static String doJsonPost(@Comment("url")String apiUrl,@Comment("请求头,没有请传null") Map<String, String> headers, @Comment("json参数")String jsonParam) {try {return adaptor.doPost(apiUrl, headers, jsonParam);} catch (UnsupportedEncodingException e) {throw new ServiceException(MyErrorCode.HTTP_PARAM_JSON.getStatus(),MyErrorCode.HTTP_PARAM_JSON.getMsg());}}public static String doDelete(String url, Map<String, String> headers, HashMap<String, Object> params) {return adaptor.doDelete(url, headers, params);}public static String getUrlWithParams(String url, Map<String, Object> params) {boolean first = true;StringBuilder sb = new StringBuilder(url);for (String key : params.keySet()) {char ch = '&';if (first == true) {ch = '?';first = false;}String value = params.get(key).toString();try {String sval = URLEncoder.encode(value, UTF_8);sb.append(ch).append(key).append("=").append(sval);} catch (UnsupportedEncodingException e) {}}return sb.toString();}public static Map<String, Object> convent2Map(Object b) {Map<String, Object> params = new HashMap<>();for(Field field: b.getClass().getDeclaredFields()) {field.setAccessible(true);Object val = null;try {val = field.get(b);} catch (IllegalArgumentException | IllegalAccessException e) {}if(val != null) {params.put(field.getName(), val);}}return params;}}
PooledHttpClientAdaptor
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;import javax.net.ssl.SSLContext;import cn.hutool.core.util.StrUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import com.alibaba.fastjson.JSON;/*** @author JGMa**/
public class PooledHttpClientAdaptor {private static final Logger logger = LoggerFactory.getLogger(PooledHttpClientAdaptor.class);private static final int DEFAULT_POOL_MAX_TOTAL = 200;private static final int DEFAULT_POOL_MAX_PER_ROUTE = 200;private static final int DEFAULT_CONNECT_TIMEOUT = 10000;private static final int DEFAULT_CONNECT_REQUEST_TIMEOUT = 10000;private static final int DEFAULT_SOCKET_TIMEOUT = 60000;private PoolingHttpClientConnectionManager gcm = null;private CloseableHttpClient httpClient = null;private IdleConnectionMonitorThread idleThread = null;// 连接池的最大连接数private final int maxTotal;// 连接池按route配置的最大连接数private final int maxPerRoute;// tcp connect的超时时间private final int connectTimeout;// 从连接池获取连接的超时时间private final int connectRequestTimeout;// tcp io的读写超时时间private final int socketTimeout;public PooledHttpClientAdaptor() {this(PooledHttpClientAdaptor.DEFAULT_POOL_MAX_TOTAL,PooledHttpClientAdaptor.DEFAULT_POOL_MAX_PER_ROUTE,PooledHttpClientAdaptor.DEFAULT_CONNECT_TIMEOUT,PooledHttpClientAdaptor.DEFAULT_CONNECT_REQUEST_TIMEOUT,PooledHttpClientAdaptor.DEFAULT_SOCKET_TIMEOUT);}public PooledHttpClientAdaptor(int maxTotal, int maxPerRoute, int connectTimeout, int connectRequestTimeout, int socketTimeout ) {this.maxTotal = maxTotal;this.maxPerRoute = maxPerRoute;this.connectTimeout = connectTimeout;this.connectRequestTimeout = connectRequestTimeout;this.socketTimeout = socketTimeout;final SSLConnectionSocketFactory sslsf;try {sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(),NoopHostnameVerifier.INSTANCE);} catch (NoSuchAlgorithmException e) {throw new RuntimeException(e);}Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();this.gcm = new PoolingHttpClientConnectionManager(registry);this.gcm.setMaxTotal(this.maxTotal);this.gcm.setDefaultMaxPerRoute(this.maxPerRoute);RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(this.connectTimeout) // 设置连接超时.setSocketTimeout(this.socketTimeout) // 设置读取超时.setConnectionRequestTimeout(this.connectRequestTimeout) // 设置从连接池获取连接实例的超时.build();HttpClientBuilder httpClientBuilder = HttpClients.custom();httpClient = httpClientBuilder.setConnectionManager(this.gcm).setDefaultRequestConfig(requestConfig).build();idleThread = new IdleConnectionMonitorThread(this.gcm);idleThread.start();}public String doGet(String url) {return this.doGet(url, Collections.emptyMap(), Collections.emptyMap());}public String doGet(String url, Map<String, Object> params) {return this.doGet(url, Collections.emptyMap(), params);}public String doGet(String url, Map<String, String> headers,Map<String, Object> params) {logger.debug("doGet url:" + url + ". headers :" + JSON.toJSONString(headers) + ". params :" + JSON.toJSONString(params));// *) 构建GET请求头String apiUrl = HttpUtil.getUrlWithParams(url, params);HttpGet httpGet = new HttpGet(apiUrl);// *) 设置header信息if ( headers != null && headers.size() > 0 ) {for (Map.Entry<String, String> entry : headers.entrySet()) {httpGet.addHeader(entry.getKey(), entry.getValue());}}CloseableHttpResponse response = null;try {response = httpClient.execute(httpGet);if (response == null || response.getStatusLine() == null) {return null;}int statusCode = response.getStatusLine().getStatusCode();if ( statusCode == HttpStatus.SC_OK ) {HttpEntity entityRes = response.getEntity();if (entityRes != null) {return EntityUtils.toString(entityRes, HttpUtil.UTF_8);}}return null;} catch (IOException e) {logger.error(e.getMessage(), e);} finally {if ( response != null ) {try {response.close();} catch (IOException e) {}}}return null;}public String doPost(String apiUrl, Map<String, Object> params) {return this.doPost(apiUrl, Collections.emptyMap(), params);}public String doPost(String apiUrl,Map<String, String> headers,String jsonParam) throws UnsupportedEncodingException {logger.debug("doPost url:" + apiUrl + ". headers :" + JSON.toJSONString(headers) + ". jsonParam :" + jsonParam);HttpPost httpPost = new HttpPost(apiUrl);// 配置请求headersif ( headers != null && headers.size() > 0 ) {for (Map.Entry<String, String> entry : headers.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());}}// 配置请求参数if ( StrUtil.isNotBlank(jsonParam)) {StringEntity jsonEntity = new StringEntity(jsonParam);httpPost.setEntity(jsonEntity);httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");}CloseableHttpResponse response = null;try {response = httpClient.execute(httpPost);if (response == null || response.getStatusLine() == null) {return null;}int statusCode = response.getStatusLine().getStatusCode();if ( statusCode == HttpStatus.SC_OK ) {HttpEntity entityRes = response.getEntity();if ( entityRes != null ) {return EntityUtils.toString(entityRes, HttpUtil.UTF_8);}}return null;} catch (IOException e) {logger.error(e.getMessage(), e);} finally {if (response != null) {try {response.close();} catch (IOException e) {}}}return null;}public String doPost(String apiUrl, Map<String, String> headers, Map<String, Object> params) {logger.debug("doPost url:" + apiUrl + ". headers :" + JSON.toJSONString(headers) + ". params :" + JSON.toJSONString(params));HttpPost httpPost = new HttpPost(apiUrl);// 配置请求headersif ( headers != null && headers.size() > 0 ) {for (Map.Entry<String, String> entry : headers.entrySet()) {httpPost.addHeader(entry.getKey(), entry.getValue());}}// 配置请求参数if ( params != null && params.size() > 0 ) {HttpEntity entityReq = getUrlEncodedFormEntity(params);httpPost.setEntity(entityReq);}CloseableHttpResponse response = null;try {response = httpClient.execute(httpPost);if (response == null || response.getStatusLine() == null) {return null;}int statusCode = response.getStatusLine().getStatusCode();if ( statusCode == HttpStatus.SC_OK ) {HttpEntity entityRes = response.getEntity();if ( entityRes != null ) {return EntityUtils.toString(entityRes, HttpUtil.UTF_8);}}return null;} catch (IOException e) {logger.error(e.getMessage(), e);} finally {if (response != null) {try {response.close();} catch (IOException e) {}}}return null;}public String doDelete(String url, Map<String, String> headers, Map<String, Object> params) {logger.info("doDelete url:" + url + ". headers :" + JSON.toJSONString(headers) + ". params :" + JSON.toJSONString(params));HttpDelete httpDelete = new HttpDelete(url);// *) 设置header信息if ( headers != null && headers.size() > 0 ) {for (Map.Entry<String, String> entry : headers.entrySet()) {httpDelete.addHeader(entry.getKey(), entry.getValue());}}CloseableHttpResponse response = null;try {response = httpClient.execute(httpDelete);if (response == null || response.getStatusLine() == null) {return null;}int statusCode = response.getStatusLine().getStatusCode();if ( statusCode == HttpStatus.SC_OK ) {HttpEntity entityRes = response.getEntity();if (entityRes != null) {return EntityUtils.toString(entityRes, HttpUtil.UTF_8);}}return null;} catch (IOException e) {logger.error(e.getMessage(), e);} finally {if ( response != null ) {try {response.close();} catch (IOException e) {}}}return null;}private HttpEntity getUrlEncodedFormEntity(Map<String, Object> params) {List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());for (Map.Entry<String, Object> entry : params.entrySet()) {NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());pairList.add(pair);}return new UrlEncodedFormEntity(pairList, Charset.forName(HttpUtil.UTF_8));}public void shutdown() {idleThread.shutdown();}// 监控有异常的链接private class IdleConnectionMonitorThread extends Thread {private final HttpClientConnectionManager connMgr;private volatile boolean exitFlag = false;public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {this.connMgr = connMgr;setDaemon(true);}@Overridepublic void run() {while (!this.exitFlag) {synchronized (this) {try {this.wait(2000);} catch (InterruptedException e) {e.printStackTrace();}}// 关闭失效的连接connMgr.closeExpiredConnections();// 可选的, 关闭30秒内不活动的连接connMgr.closeIdleConnections(30, TimeUnit.SECONDS);}}public void shutdown() {this.exitFlag = true;synchronized (this) {notify();}}}}
相关文章:
HttpUtils带连接池
准备祖传了,有问题欢迎大家指正。 HttpUtil import com.txlc.cloud.commons.exception.ServiceException; import com.txlc.dwh.common.constants.MyErrorCode; import org.ssssssss.script.annotation.Comment;import java.io.UnsupportedEncodingException; impo…...
智慧养殖:浅谈视频监控与AI智能识别技术助力奶牛高效、智慧养殖
一、方案背景 随着科技的飞速发展,智能化养殖逐渐成为现代畜牧业的发展趋势。人工智能技术、物联网、视频技术、云计算、大数据等新兴技术,正在为奶牛养殖业带来全新的变革。越来越多的牧场、养殖场开始运用新技术来进行智能监管、提高生产效率、降低生…...
一文总结提示工程框架,除了CoT还有ToT、GoT、AoT、SoT、PoT
夕小瑶科技说 原创 编译 | 谢年年 大语言模型LLM被视为一个巨大的知识库,它可以根据你提出问题或陈述的方式来提供答案。就像人类可能会根据问题的不同提供不同的答案一样,LLM也可以根据输入的不同给出不同的答案。因此,你的问题或陈述方式就…...
Java面试笔试acm版输入
首先区分scanner.nextInt()//输入一个整数,只能读取一个数,空格就停止。 scanner.next()//输入字符串,只能读取一个字符串,空格就停止,但是逗号不停止。 scanner.nextLine() 读取一行,换行停止,…...
新手怎样快速上手接口测试?掌握这几个知识点直接起飞!
接口测试是测试系统组件间接口的一种方式,接口测试主要用于检测外部系统与系统之间以及内部各个子系统之间的交互点。测试的重点是检查数据的增删改查操作,以及系统之间的逻辑关系等。 接口的几种类型 接口的类型包括:post ,get&…...
IDEA 启动 java web 老项目
背景:一套 java web 老代码,使用 eclipse 工具开发。内网,无 eclipse 开发工具,只有 IDEA。 代码目录结构如下: demo/.settings/* demo/src/com/demo/controller/* demo/webapp/js/* demo/webapp/jsp/* demo/webapp/M…...
软路由和硬路由的区别是什么,性价比与可玩性分析
软路由和硬路由是两种不同类型的路由器设备,它们在基本原理、功能、性能和灵活性等方面存在一些区别: 硬件:软路由是基于一台普通的计算机或服务器,通过软件来实现路由器的功能;而硬路由是专门设计的硬件设备ÿ…...
《TCP/IP网络编程》阅读笔记--多线程服务器端的实现
目录 1--多线程的优点 2--进程和线程的差异 3--线程创建 4--线程使用 5--线程安全问题 6--互斥量 7--信号量 8--线程销毁 9--多线程并发聊天程序 9-1--服务器端 9-2--客户端 9-3--测试结果 1--多线程的优点 多进程服务器的缺点: ① 创建进程的过程会带来…...
修改el-card的header的背景颜色
修改el-card的header的背景颜色 1.修改默认样式 好处是当前页面的所有的el-card都会变化 页面卡片: <el-card class"box-card" ><div slot"header" class"clearfix"><span>卡片名称</span><el-button s…...
ubuntu系统中查看打开的端口
要查看Ubuntu系统中已打开的端口及其相关信息,可以使用以下方法: 打开终端(Terminal)。 运行以下命令以查看当前系统中的端口使用情况: sudo netstat -tuln这将显示所有已打开的端口及其相关信息,包括监听…...
Datax从mysql同步数据到HDFS
在实际使用Datax的时候,比较常用的是同步业务数据(mysql中的数据)到HDFS来实现数仓的创建,那么怎么实现呢?我们一步步来实现(基于Datax 3.0.0) 1、检查环境,需要安装完一个Datax&am…...
使用 Selenium 或其他工具模拟浏览器使用及语法代码
使用Selenium模拟浏览器使用的代码示例如下: from selenium import webdriverfrom selenium.webdriver.common.keys import Keys# 创建浏览器驱动实例driver webdriver.Chrome()# 打开网页driver.get("https://www.example.com")# 查找并填写表单search_…...
华为手机如何开启设置健康使用手机模式限制孩子玩手机时间?
华为手机如何开启设置健康使用手机模式限制孩子玩手机时间? 1、在手机上找到「设置」并点击打开; 2、在设置内找到「健康使用手机」并点击进入; 3、开启健康使用手机后,选择孩子使用; 4、在健康使用手机内,…...
【Linux】线程池 | 自旋锁 | 读写锁
文章目录 一、线程池1. 线程池模型和应用场景2. 单例模式实现线程池(懒汉模式) 二、其他常见的锁1. STL、智能指针和线程安全2. 其他常见的锁 三、读者写者问题1. 读者写者模型2. 读写锁 一、线程池 1. 线程池模型和应用场景 线程池是一种线程使用模式。线程过多会带来调度开…...
[网鼎杯 2020 青龙组]bang 题解
写一道安卓题的WP 首先你需要一个root机,使用真机或者虚拟机,根据网上的教程刷机并获取root 我使用真机调试,pixel2 讲安卓包下载到真机 在PC端配置frida 对应版本的server传送到/data/local/tmp 然后进行以上操作,启动server …...
创建环境时提示:ERROR conda.core.link:_execute(502)
创建环境时提示:ERROR conda.core.link:_execute(502) 创建环境最后Executing transaction,失败,提示如下: Preparing transaction: done Verifying transaction: done Executing transaction: failed ERROR conda.core.link:_e…...
Python150题day07
1.5集合练习题 集合间的运算 lst1 [1, 2, 3, 5, 6, 3, 2] lst2 [2, 5, 7, 9] 哪些整数既在Ist1中,也在Ist2中哪些整数在Ist1中,不在Ist2中两个列表一共有哪些整数 虽然题目问的是两个列表之间的问题,但是用列表解答的效率很低,…...
LeetCode 2596. 检查骑士巡视方案
【LetMeFly】2596.检查骑士巡视方案 力扣题目链接:https://leetcode.cn/problems/check-knight-tour-configuration/ 骑士在一张 n x n 的棋盘上巡视。在有效的巡视方案中,骑士会从棋盘的 左上角 出发,并且访问棋盘上的每个格子 恰好一次 。…...
大数据学习1.0-目录
学习内容持续更新ing 1.大数据学习1.1-Centos8虚拟机安装 大数据学习1.0-Centos8虚拟机安装_汉卿HanQ的博客-CSDN博客 2.大数据学习1.2-yum配置 大数据学习1.2-yum配置_汉卿HanQ的博客-CSDN博客 3.大数据学习1.3-xShell配置jdk 大数据学习1.3-xShell配置jdk_汉卿HanQ的博客…...
无涯教程-JavaScript - POWER函数
描述 POWER函数返回加到幂的数字的输出。 语法 POWER (number, power)争论 Argument描述Required/OptionalNumber 基数。 它可以是任何实数。 RequiredPowerThe exponent to which the base number is raised.Required Notes 可以使用" ^"运算符代替POWER来指示…...
mongodb源码分析session执行handleRequest命令find过程
mongo/transport/service_state_machine.cpp已经分析startSession创建ASIOSession过程,并且验证connection是否超过限制ASIOSession和connection是循环接受客户端命令,把数据流转换成Message,状态转变流程是:State::Created 》 St…...
大语言模型如何处理长文本?常用文本分割技术详解
为什么需要文本分割? 引言:为什么需要文本分割?一、基础文本分割方法1. 按段落分割(Paragraph Splitting)2. 按句子分割(Sentence Splitting)二、高级文本分割策略3. 重叠分割(Sliding Window)4. 递归分割(Recursive Splitting)三、生产级工具推荐5. 使用LangChain的…...
初学 pytest 记录
安装 pip install pytest用例可以是函数也可以是类中的方法 def test_func():print()class TestAdd: # def __init__(self): 在 pytest 中不可以使用__init__方法 # self.cc 12345 pytest.mark.api def test_str(self):res add(1, 2)assert res 12def test_int(self):r…...
在web-view 加载的本地及远程HTML中调用uniapp的API及网页和vue页面是如何通讯的?
uni-app 中 Web-view 与 Vue 页面的通讯机制详解 一、Web-view 简介 Web-view 是 uni-app 提供的一个重要组件,用于在原生应用中加载 HTML 页面: 支持加载本地 HTML 文件支持加载远程 HTML 页面实现 Web 与原生的双向通讯可用于嵌入第三方网页或 H5 应…...
Python ROS2【机器人中间件框架】 简介
销量过万TEEIS德国护膝夏天用薄款 优惠券冠生园 百花蜂蜜428g 挤压瓶纯蜂蜜巨奇严选 鞋子除臭剂360ml 多芬身体磨砂膏280g健70%-75%酒精消毒棉片湿巾1418cm 80片/袋3袋大包清洁食品用消毒 优惠券AIMORNY52朵红玫瑰永生香皂花同城配送非鲜花七夕情人节生日礼物送女友 热卖妙洁棉…...
【从零学习JVM|第三篇】类的生命周期(高频面试题)
前言: 在Java编程中,类的生命周期是指类从被加载到内存中开始,到被卸载出内存为止的整个过程。了解类的生命周期对于理解Java程序的运行机制以及性能优化非常重要。本文会深入探寻类的生命周期,让读者对此有深刻印象。 目录 …...
leetcode73-矩阵置零
leetcode 73 思路 记录 0 元素的位置:遍历整个矩阵,找出所有值为 0 的元素,并将它们的坐标记录在数组zeroPosition中置零操作:遍历记录的所有 0 元素位置,将每个位置对应的行和列的所有元素置为 0 具体步骤 初始化…...
JavaScript 标签加载
目录 JavaScript 标签加载script 标签的 async 和 defer 属性,分别代表什么,有什么区别1. 普通 script 标签2. async 属性3. defer 属性4. type"module"5. 各种加载方式的对比6. 使用建议 JavaScript 标签加载 script 标签的 async 和 defer …...
OpenGL-什么是软OpenGL/软渲染/软光栅?
软OpenGL(Software OpenGL)或者软渲染指完全通过CPU模拟实现的OpenGL渲染方式(包括几何处理、光栅化、着色等),不依赖GPU硬件加速。这种模式通常性能较低,但兼容性极强,常用于不支持硬件加速…...
开疆智能Ethernet/IP转Modbus网关连接鸣志步进电机驱动器配置案例
在工业自动化控制系统中,常常会遇到不同品牌和通信协议的设备需要协同工作的情况。本案例中,客户现场采用了 罗克韦尔PLC,但需要控制的变频器仅支持 ModbusRTU 协议。为了实现PLC 对变频器的有效控制与监控,引入了开疆智能Etherne…...
