HttpClientManager
HttpClientManger
package com.gateway.http.client; import com.fasterxml.jackson.core.type.TypeReference;
import com.apollo.common.http.HttpMethod;
import com.apollo.gateway.common.HttpConstant;
import com.apollo.gateway.util.JsonUtil;
import okhttp3.*;
import okhttp3.internal.Util;
import okhttp3.logging.HttpLoggingInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; /**
*
* @author muzhi
* @date 2022-11-21 19:17:28
*/
public class HttpClientManager {
private static final Logger log = LoggerFactory.getLogger(HttpClientManager.class);
private static final Map<Long, OkHttpClient> map = new HashMap<>();
private static final Long TIMEOUT = 5000L;
private <T> T request(HttpMethod httpMethod, OkHttpClient httpClient, final String url, Map<String, String> header, final Object param,
final TypeReference<T> typeReference) throws IOException {
final Request.Builder builder = new Request.Builder();
//add header
if(header != null && !header.isEmpty()){
header.forEach((k, v) -> {
if(v != null){
builder.addHeader(k, v);
}
});
} switch (httpMethod){
case POST:
if(param != null){
if(param instanceof byte[]){
builder.post(new ByteRequestBody((byte[]) param));
} else {
String content = JsonUtil.toJson(param);
RequestBody requestBody = RequestBody.create(HttpConstant.JSON_MEDIA_TYPE, content);
builder.post(requestBody);
}
} else {
builder.post(RequestBody.create(HttpConstant.JSON_MEDIA_TYPE, "{}"));
}
builder.url(url);
break;
case GET:
StringBuilder str = new StringBuilder(url);
if(param != null && param instanceof Map){
if(!url.contains("?")){
str.append("?");
}
Map body = (Map) param;
if(body != null && !body.isEmpty()){
StringJoiner joiner = new StringJoiner("", "&", "");
body.forEach((k, v) -> {
joiner.add(k + "=" + v);
});
str.append("&").append(joiner.toString());
}
}
builder.url(str.toString()).get();
break;
default:
throw new RuntimeException("request method not supported");
} Response execute = httpClient.newCall(builder.build()).execute();
String response = execute.body().string();
if(typeReference == null){
return (T) response;
}
return JsonUtil.readValue(response, typeReference);
} private <T> T request(HttpMethod httpMethod, final String accessCode, final String url, final Object param,
final TypeReference<T> typeReference) throws IOException {
OkHttpClient httpClient = map.computeIfAbsent(TIMEOUT, k -> buildHttpClient());
Map<String, String> header = new HashMap<>();
return request(httpMethod, httpClient, url, header, param, typeReference);
} // public <T> T post(final String accessCode, final String url, final Object param,
// final TypeReference<T> typeReference, Long timeout) throws IOException {
// return request(HttpMethod.POST, accessCode, url, param, typeReference, timeout);
// } public <T> T post(final String accessCode, final String url, final Object param,
final TypeReference<T> typeReference) throws IOException {
return request(HttpMethod.POST, accessCode, url, param, typeReference);
} private OkHttpClient buildHttpClient() {
try {
OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
// add timeout
okHttpBuilder
.readTimeout(60_000, TimeUnit.MILLISECONDS)
.connectTimeout(60_000, TimeUnit.MILLISECONDS)
.callTimeout(60_000, TimeUnit.MILLISECONDS)
.connectionPool(new ConnectionPool(500, 5 * 60, TimeUnit.SECONDS)); // Install the all-trusting trust manager
//okHttpBuilder.addInterceptor(new RetryInterceptor(httpClientParam.getMaxRetry(), httpClientParam.getRetryInterval()));
configNoSSL(okHttpBuilder);
configDispatcher(okHttpBuilder);
configLogBody(okHttpBuilder, true);
return okHttpBuilder.build();
} catch (Exception e) {
log.error("buildHttpClient error", e);
}
return null;
} private void configDispatcher(final OkHttpClient.Builder okHttpBuilder) {
ThreadPoolExecutor executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<>(),
Util.threadFactory("lambada-OkHttp-Dispatcher", false)
);
Dispatcher dispatcher = new Dispatcher(executorService);
dispatcher.setMaxRequests(200);
dispatcher.setMaxRequestsPerHost(200);
okHttpBuilder.dispatcher(dispatcher);
} private static void configLogBody(OkHttpClient.Builder okHttpBuilder, boolean ignoreLargeContent) {
HttpLogger logger = new HttpLogger();
logger.setIgnoreLargeContent(ignoreLargeContent);
HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(logger);
logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpBuilder.addNetworkInterceptor(logInterceptor);
} private static void configNoSSL(OkHttpClient.Builder okHttpBuilder) throws KeyManagementException, NoSuchAlgorithmException {
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
okHttpBuilder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
okHttpBuilder.hostnameVerifier((hostname, session) -> true);
} private static final TrustManager[] trustAllCerts =
new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain, String authType) {
} @Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain, String authType) {
} @Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
}
};
}
HttpClientManager的更多相关文章
- Using HttpClient properly to avoid CLOSE_WAIT TCP connections
Apache的HttpComponent组件,用的人不在少数.但是能用好的人,却微乎其微,为什么?很简单,TCP里面的细节实现不是每个人都能捕获到的(细节是魔鬼),像并发请求控制&资源释放,N ...
- Web API的接口访问安全性
使用签名获取Token 首先我们自定义appkey.appSecret.可用GUID随机生成,AppSecret要不定期更换.然后放到配置文件中. Appkey=1AF62C68-B970-46E7- ...
- httpclient httpclient连接回收
httpclient连接释放 httpClient必须releaseConnection,但不是abort.因为releaseconnection是归还连接到到连接池,而abort是直接抛弃这个连接, ...
随机推荐
- CSharp的Where底层实现
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using Syst ...
- 使用Pydantic和SqlAlchemy实现树形列表数据(自引用表关系)的处理,以及递归方式处理数据差异
在我的设计框架业务中,字典大类.部门机构.系统菜单等这些表,都存在id.pid的字段,主要是作为自引用关系,实现树形列表数据的处理的,因为这样可以实现无限层级的树形列表.在实际使用Pydantic和S ...
- ERQ:32位转5位仅掉些许精度,来看看两段式后训练量化 | ICML 2024
后训练量化(PTQ)在视觉Transformer(ViTs)领域引起了广泛关注,因为它在模型压缩方面表现出了高效率.然而,现有的方法通常忽视了量化权重和激活之间复杂的相互依赖关系,导致了相当大的量化误 ...
- 使用 Prometheus 在 KubeSphere 上监控 KubeEdge 边缘节点(Jetson) CPU、GPU 状态
作者:朱亚光,之江实验室工程师,云原生/开源爱好者. KubeSphere 边缘节点的可观测性 在边缘计算场景下,KubeSphere 基于 KubeEdge 实现应用与工作负载在云端与边缘节点的统一 ...
- KubeSphere 社区双周报 | KubeKey v3.0.7 发布 | 2023-02-03
KubeSphere 从诞生的第一天起便秉持着开源.开放的理念,并且以社区的方式成长,如今 KubeSphere 已经成为全球最受欢迎的开源容器平台之一.这些都离不开社区小伙伴的共同努力,你们为 Ku ...
- 云原生爱好者周刊:为 DevOps 流水线准备的 macOS 虚拟化工具
开源项目推荐 Tart Tart 是一个虚拟化工具集,用于构建.运行和管理 Apple Silicon 芯片 macOS 上的虚拟机,主要目的是为 CI 流水线的特殊任务提供运行环境.主要亮点: 使用 ...
- 云原生爱好者周刊:使用 Cilium 和 Grafana 实现无侵入可观测性
开源项目推荐 Cilium Grafana Observability Demo 这个项目由 Cilium 母公司 Isovalent 开源,提供了一个 Demo,使用 Cilium.OpenTele ...
- MYSQL SQL做题总结
一.关于join 1.内外左右连接 2.交叉联结(corss join) 使用交叉联结会将两个表中所有的数据两两组合.如下图,是对表"text"自身进行交叉联结的结果: 3.三表双 ...
- 《用广义CNOT门产生质数幂维的图态》
参考文献:Graph states of prime-power dimension from generalized CNOT quantum circuit 主机文件:<2016质数图态.p ...
- 基于Java+SpringBoot+Mysql实现的古诗词平台功能设计与实现八
一.前言介绍: 1.1 项目摘要 随着信息技术的迅猛发展和数字化时代的到来,传统文化与现代科技的融合已成为一种趋势.古诗词作为中华民族的文化瑰宝,具有深厚的历史底蕴和独特的艺术魅力.然而,在现代社会中 ...