Sfoglia il codice sorgente

解决外部http调用连接超时导致系统卡断问题;

codingliang 2 anni fa
parent
commit
7cbe2168a5
1 ha cambiato i file con 16 aggiunte e 1 eliminazioni
  1. 16 1
      src/main/java/com/sqx/modules/utils/HttpClientUtil.java

+ 16 - 1
src/main/java/com/sqx/modules/utils/HttpClientUtil.java

@@ -2,6 +2,7 @@ package com.sqx.modules.utils;
 
 import org.apache.http.HttpEntity;
 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.HttpGet;
@@ -26,8 +27,18 @@ import java.util.Map;
 
 public class HttpClientUtil {
 
-    public static String doGet(String url, Map<String, String> param) {
+    // http请求配置
+    private static RequestConfig config = RequestConfig.custom()
+                                                // 连接超时时间(毫秒)
+                                                .setConnectTimeout(5000)
+                                                // 数据读取超时时间(毫秒)
+                                                .setSocketTimeout(10000)
+                                                // 连接不夠用的等待时间(毫秒)
+                                                .setConnectionRequestTimeout(1000)
+                                                .build();
+
 
+    public static String doGet(String url, Map<String, String> param) {
         // 创建Httpclient对象
         CloseableHttpClient httpclient = HttpClients.createDefault();
 
@@ -45,6 +56,7 @@ public class HttpClientUtil {
 
             // 创建http GET请求
             HttpGet httpGet = new HttpGet(uri);
+            httpGet.setConfig(config);
             // 执行请求
             response = httpclient.execute(httpGet);
             // 判断返回状态是否为200
@@ -78,6 +90,7 @@ public class HttpClientUtil {
         try {
             // 创建Http Post请求
             HttpPost httpPost = new HttpPost(url);
+            httpPost.setConfig(config);
             // 创建参数列表
             if (param != null) {
                 List<NameValuePair> paramList = new ArrayList<>();
@@ -116,6 +129,7 @@ public class HttpClientUtil {
         try {
             // 创建Http Post请求
             HttpPost httpPost = new HttpPost(url);
+            httpPost.setConfig(config);
             // 创建请求内容
             StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
             httpPost.setEntity(entity);
@@ -145,6 +159,7 @@ public class HttpClientUtil {
         CloseableHttpClient httpclient = HttpClients.createDefault();
         // 创建httppost
         HttpPost httppost = new HttpPost(URL);
+        httppost.setConfig(config);
         httppost.addHeader("Content-type", "application/json; charset=utf-8");
         httppost.setHeader("Accept", "application/json");
         try {