perf:移除hutool的http模块,使用okhttp3

This commit is contained in:
曾文豪
2024-07-30 13:39:45 +08:00
parent 450d1fb869
commit 333d283e24
19 changed files with 351 additions and 65 deletions

View File

@@ -32,8 +32,21 @@
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<artifactId>hutool-bom</artifactId>
<version>5.8.16</version>
<type>pom</type>
<exclusions>
<exclusion>
<groupId>cn.hutool</groupId>
<artifactId>hutool-http</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
<!-- MySql驱动 -->

View File

@@ -4,9 +4,7 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.comparator.VersionComparator;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpGlobalConfig;
import cn.hutool.log.LogFactory;
import com.tiesheng.util.exception.ApiException;
import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -14,7 +12,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
@@ -40,14 +37,6 @@ public class GlobalConfig {
private HashMap<String, String> ext;
@PostConstruct
public void init() {
// 默认10s的超时时间
HttpGlobalConfig.setTimeout(10 * 1000);
// 最多重定向3次
HttpGlobalConfig.setMaxRedirectCount(3);
}
///////////////////////////////////////////////////////////////////////////
// 逻辑方法
///////////////////////////////////////////////////////////////////////////

View File

@@ -1,9 +1,9 @@
package com.tiesheng.util.config;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.log.LogFactory;
import com.tiesheng.util.ip2region.Searcher;
import com.tiesheng.util.service.http.OkHttpUtil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@@ -27,7 +27,7 @@ public class Ip2regionConfig {
public void downloadDbFile() {
if (!FileUtil.exist(dbPath)) {
LogFactory.get().info("download ip2region file start");
HttpUtil.downloadFile(dbUrl, dbPath);
OkHttpUtil.downloadFile(dbUrl, dbPath);
LogFactory.get().info("download ip2region file finish");
}
}

View File

@@ -6,8 +6,8 @@ import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import com.tiesheng.util.config.GlobalConfig;
import com.tiesheng.util.service.http.OkHttpUtil;
public class FileUploadPath {
@@ -71,7 +71,7 @@ public class FileUploadPath {
String newFileName = UPLOAD_FOLDER + StrUtil.subAfter(httpUrl, UPLOAD_FOLDER, true);
FileUploadPath uploadPath = file(newFileName);
if (!FileUtil.exist(uploadPath.getAbsolutePath())) {
HttpUtil.downloadFile(httpUrl, uploadPath.getAbsolutePath());
OkHttpUtil.downloadFile(httpUrl, uploadPath.getAbsolutePath());
}
return uploadPath.getHttpPath();

View File

@@ -0,0 +1,37 @@
package com.tiesheng.util.service.http;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.LogFactory;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
public class HttpLogInterceptor implements Interceptor {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) {
Request request = chain.request();
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
response = new Response.Builder()
.request(request)
.body(OkHttpUtil.ofJsonResponse(JSONUtil.createObj()
.putOpt("code", -1)
.putOpt("message", e.getMessage())
.putOpt("exception", e)
.toString()))
.code(200).build();
}
LogFactory.get().info("url: {}body: {}", request.url(), response.body().contentType().toString());
return response;
}
}

View File

@@ -0,0 +1,52 @@
package com.tiesheng.util.service.http;
import okhttp3.Interceptor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class OkHttpConfig implements ApplicationListener<ContextRefreshedEvent> {
/**
* 全局连接超时
*/
public static int GLOBAL_TIMEOUT = 5 * 1000;
/**
* 全局拦截器
*/
public static final List<Interceptor> INTERCEPTORS = new ArrayList<>();
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
Map<String, Interceptor> beansOfType = applicationContext.getBeansOfType(Interceptor.class);
for (Map.Entry<String, Interceptor> entry : beansOfType.entrySet()) {
INTERCEPTORS.add(entry.getValue());
}
}
///////////////////////////////////////////////////////////////////////////
// setter、getter
///////////////////////////////////////////////////////////////////////////
/**
* 设置全局超时时间
*
* @param timeout
*/
public static void setGlobalTimeout(int timeout) {
GLOBAL_TIMEOUT = timeout;
}
}

View File

@@ -0,0 +1,167 @@
package com.tiesheng.util.service.http;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.net.url.UrlQuery;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import okhttp3.*;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class OkHttpUtil {
/**
* 创建客户端
*
* @return
*/
public static OkHttpClient.Builder ofHttpClient() {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(OkHttpConfig.GLOBAL_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(OkHttpConfig.GLOBAL_TIMEOUT, TimeUnit.MILLISECONDS);
for (Interceptor interceptor : OkHttpConfig.INTERCEPTORS) {
builder.addInterceptor(interceptor);
}
return builder;
}
public static Request ofRequest(String method, String url, RequestBody body) {
return new Request.Builder()
.url(url).method(method, body).build();
}
public static Request ofGet(String url) {
return ofRequest("GET", url, null);
}
public static Request ofPost(String url, JSONObject body) {
return ofRequest("POST", url, ofJsonBody(body.toString()));
}
public static Request ofPost(String url, RequestBody body) {
return ofRequest("POST", url, body);
}
public static RequestBody ofJsonBody(String json) {
return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
}
public static ResponseBody ofJsonResponse(String json) {
return ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), json);
}
public static MultipartBody.Builder ofMultipartBody(File file) {
return new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("application/octet-stream"), file));
}
///////////////////////////////////////////////////////////////////////////
// get请求
///////////////////////////////////////////////////////////////////////////
public static String get(String urlString) {
return get(urlString, OkHttpConfig.GLOBAL_TIMEOUT);
}
public static String get(String urlString, Map<String, Object> queryMap) {
String build = UrlQuery.of(queryMap).build(CharsetUtil.CHARSET_UTF_8);
if (StrUtil.contains(urlString, "?")) {
urlString = urlString + "&" + build;
} else {
urlString = urlString + "?" + build;
}
return get(urlString, OkHttpConfig.GLOBAL_TIMEOUT);
}
public static String get(String urlString, int timeout) {
try {
return ofHttpClient().connectTimeout(timeout, TimeUnit.MILLISECONDS)
.build().newCall(ofGet(urlString)).execute().body().string();
} catch (IOException ignored) {
}
return null;
}
///////////////////////////////////////////////////////////////////////////
// Post请求
///////////////////////////////////////////////////////////////////////////
public static String post(String urlString, Map<String, String> paramMap) {
return post(urlString, paramMap, OkHttpConfig.GLOBAL_TIMEOUT);
}
public static String post(String urlString, Map<String, String> paramMap, int timeout) {
FormBody.Builder formBuilder = new FormBody.Builder();
for (String key : paramMap.keySet()) {
formBuilder.add(key, paramMap.get(key));
}
return post(urlString, formBuilder.build(), timeout);
}
public static String post(String urlString, JSONObject body) {
return post(urlString, body, OkHttpConfig.GLOBAL_TIMEOUT);
}
public static String post(String urlString, JSONObject body, int timeout) {
return post(urlString, ofJsonBody(body.toString()), timeout);
}
public static String post(String urlString, RequestBody body, int timeout) {
try {
return ofHttpClient().connectTimeout(timeout, TimeUnit.MILLISECONDS)
.build().newCall(ofPost(urlString, body)).execute().body().string();
} catch (IOException ignored) {
}
return null;
}
///////////////////////////////////////////////////////////////////////////
// Download下载文件
///////////////////////////////////////////////////////////////////////////
public static File downloadFile(String url, String destFile) {
return downloadFile(url, FileUtil.file(destFile));
}
public static File downloadFile(String url, File destFile) {
try {
Response response = ofHttpClient()
.connectTimeout(0, TimeUnit.MILLISECONDS)
.readTimeout(0, TimeUnit.MILLISECONDS)
.build().newCall(ofGet(url)).execute();
if (response.isSuccessful() && response.body() != null) {
FileUtil.writeFromStream(response.body().byteStream(), destFile);
}
return destFile;
} catch (IOException ignored) {
}
return null;
}
public static byte[] downloadBytes(String url) {
try {
Response response = ofHttpClient()
.connectTimeout(0, TimeUnit.MILLISECONDS)
.readTimeout(0, TimeUnit.MILLISECONDS)
.build().newCall(ofGet(url)).execute();
if (response.isSuccessful() && response.body() != null) {
return response.body().bytes();
}
} catch (IOException ignored) {
}
return null;
}
}