Przeglądaj źródła

修改代理请求

xueyiming 2 miesięcy temu
rodzic
commit
a5d9d831bf

+ 0 - 1
common-module/src/main/java/com/tzld/piaoquan/growth/common/common/constant/WeComConstant.java

@@ -38,7 +38,6 @@ public interface WeComConstant {
     //发送新客户欢迎语
     String POST_WE_COM_SEND_WELCOME_MSG = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/send_welcome_msg";
 
-
     //用户增加新标签
     String POST_WE_COM_ADD_USER_TAG = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag";
 }

+ 2 - 0
common-module/src/main/java/com/tzld/piaoquan/growth/common/component/HttpPoolClient.java

@@ -10,6 +10,7 @@ import org.apache.http.entity.mime.MultipartEntityBuilder;
 import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.util.EntityUtils;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.stereotype.Component;
 
 import java.io.File;
@@ -22,6 +23,7 @@ import java.nio.charset.StandardCharsets;
 public class HttpPoolClient {
 
     @Autowired
+    @Qualifier("httpClient")
     private CloseableHttpClient httpClient;
 
     public String get(String url) throws IOException {

+ 109 - 0
common-module/src/main/java/com/tzld/piaoquan/growth/common/component/ProxyHttpPoolClient.java

@@ -0,0 +1,109 @@
+package com.tzld.piaoquan.growth.common.component;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.methods.*;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.entity.mime.MultipartEntityBuilder;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.util.EntityUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Component;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.SocketTimeoutException;
+import java.nio.charset.StandardCharsets;
+
+@Slf4j
+@Component
+public class ProxyHttpPoolClient {
+
+    @Autowired
+    @Qualifier("proxyHttpClient")
+    private CloseableHttpClient httpClient;
+
+    public String get(String url) throws IOException {
+        HttpGet httpGet = new HttpGet(url);
+        return request(httpGet);
+    }
+
+    public String post(String url) throws IOException {
+        HttpPost httpPost = new HttpPost(url);
+        return request(httpPost);
+    }
+
+
+    public String post(String url, String json) throws IOException {
+        HttpPost httpPost = new HttpPost(url);
+        if (StringUtils.isBlank(json)) {
+            return request(httpPost);
+        }
+        StringEntity entity = new StringEntity(json, StandardCharsets.UTF_8);
+        entity.setContentEncoding("UTF-8");
+        entity.setContentType("application/json");
+        httpPost.setEntity(entity);
+        return request(httpPost);
+    }
+
+
+    public String post(String url, String json, String contentType) throws IOException {
+        HttpPost httpPost = new HttpPost(url);
+        if (StringUtils.isBlank(json)) {
+            return request(httpPost);
+        }
+        StringEntity entity = new StringEntity(json, StandardCharsets.UTF_8);
+        entity.setContentEncoding("UTF-8");
+        entity.setContentType(contentType);
+        httpPost.setEntity(entity);
+        return request(httpPost);
+    }
+
+    public String post(String url, File file) throws IOException {
+        HttpPost uploadFile = new HttpPost(url);
+        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
+        builder.addBinaryBody("media", file);
+        uploadFile.setEntity(builder.build());
+        return request(uploadFile);
+    }
+
+    public String request(HttpRequestBase request) throws IOException {
+
+        HttpEntity entity = null;
+        CloseableHttpResponse response = request((HttpUriRequest) request);
+        if (response == null) {
+            log.error("call api exception no response");
+            throw new RuntimeException("call api exception no response");
+        }
+        entity = response.getEntity();
+        String content = null;
+        if (entity != null) {
+            content = EntityUtils.toString(entity, "UTF-8");
+        }
+        int httpStatus = response.getStatusLine().getStatusCode();
+        if (httpStatus == HttpStatus.SC_OK) {
+            return content;
+        }
+        String path = request.getURI().toString();
+        log.error("http call api {} fail response status {} content {}", path, httpStatus, content);
+        return null;
+    }
+
+
+    public CloseableHttpResponse request(HttpUriRequest request) {
+        try {
+            return httpClient.execute(request);
+        } catch (Exception e) {
+            String path = request.getURI().toString();
+            if (e instanceof SocketTimeoutException) {
+                log.error(String.format("http timeout request url = %s .", path));
+            }
+            throw new RuntimeException(String.format("http exception request url = %s ", path), e);
+        }
+    }
+
+
+}

+ 23 - 1
common-module/src/main/java/com/tzld/piaoquan/growth/common/config/HttpClientConfig.java

@@ -1,5 +1,6 @@
 package com.tzld.piaoquan.growth.common.config;
 
+import org.apache.http.HttpHost;
 import org.apache.http.client.config.RequestConfig;
 import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
@@ -42,7 +43,7 @@ public class HttpClientConfig {
     private static final int CONNECTION_WAIT_TIMEOUT = 5000;
 
 
-    @Bean
+    @Bean(name = "httpClient")
     public CloseableHttpClient httpClient() {
 
         RequestConfig requestConfig = RequestConfig.custom()
@@ -61,4 +62,25 @@ public class HttpClientConfig {
                 .setRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT, false))
                 .build();
     }
+
+    @Bean(name = "proxyHttpClient")
+    public CloseableHttpClient proxyHttpClient() {
+        HttpHost proxy = new HttpHost("121.43.150.231", 3128, "http");
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setConnectTimeout(CONNECTION_TIMEOUT)
+                .setSocketTimeout(SOCKET_TIMEOUT)
+                .setConnectionRequestTimeout(CONNECTION_WAIT_TIMEOUT)
+                .build();
+
+        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
+        connectionManager.setMaxTotal(MAX_TOTAL); // 设置最大连接数
+        connectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE); // 每个路由的最大连接数
+
+        return HttpClientBuilder.create()
+                .setProxy(proxy)
+                .setDefaultRequestConfig(requestConfig)
+                .setConnectionManager(connectionManager)
+                .setRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT, false))
+                .build();
+    }
 }

+ 37 - 42
common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/MessageAttachmentServiceImpl.java

@@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject;
 import com.tzld.piaoquan.growth.common.common.base.CommonResponse;
 import com.tzld.piaoquan.growth.common.common.enums.MessageAttachmentTypeEnum;
 import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
+import com.tzld.piaoquan.growth.common.component.ProxyHttpPoolClient;
 import com.tzld.piaoquan.growth.common.dao.mapper.GuaranteesVideoMapper;
 import com.tzld.piaoquan.growth.common.dao.mapper.MessageAttachmentMapper;
 import com.tzld.piaoquan.growth.common.model.bo.AdPutFlowParam;
@@ -52,6 +53,9 @@ public class MessageAttachmentServiceImpl implements MessageAttachmentService {
     @Autowired
     private HttpPoolClient httpPoolClient;
 
+    @Autowired
+    private ProxyHttpPoolClient proxyHttpPoolClient;
+
     @Autowired
     private WeComAccessTokenService weComAccessTokenService;
 
@@ -329,52 +333,43 @@ public class MessageAttachmentServiceImpl implements MessageAttachmentService {
         if (StringUtils.isNotEmpty(mediaId)) {
             return mediaId;
         }
-        if (corpId == 1L) {
-            String filePath = UUID.randomUUID() + ".jpg"; // 临时文件路径
-            try {
-                HttpURLConnection httpUrl = (HttpURLConnection) new URL(cover).openConnection();
-                httpUrl.connect();
-                InputStream inputStream = httpUrl.getInputStream();
-
-                // 将文件内容写入临时文件
-                try (OutputStream outputStream = Files.newOutputStream(Paths.get(filePath))) {
-                    byte[] buffer = new byte[4096];
-                    int bytesRead;
-                    while ((bytesRead = inputStream.read(buffer)) != -1) {
-                        outputStream.write(buffer, 0, bytesRead);
-                    }
-                }
-                inputStream.close();
-                httpUrl.disconnect();
-                File file = new File(filePath);
-                String weComAccessToken = weComAccessTokenService.getWeComAccessToken(corpId);
-                String url = String.format(POST_WE_COM_MEDIA_UPLOAD + "?access_token=%s&type=%s", weComAccessToken, "image");
-                String res = httpPoolClient.post(url, file);
-                JSONObject jsonObject = JSONObject.parseObject(res);
-                if (jsonObject != null && jsonObject.getInteger("errcode") == 0) {
-                    mediaId = jsonObject.getString("media_id");
-                    redisTemplate.opsForValue().set(key, mediaId, 2, TimeUnit.DAYS);
+
+        String filePath = UUID.randomUUID() + ".jpg"; // 临时文件路径
+        try {
+            HttpURLConnection httpUrl = (HttpURLConnection) new URL(cover).openConnection();
+            httpUrl.connect();
+            InputStream inputStream = httpUrl.getInputStream();
+
+            // 将文件内容写入临时文件
+            try (OutputStream outputStream = Files.newOutputStream(Paths.get(filePath))) {
+                byte[] buffer = new byte[4096];
+                int bytesRead;
+                while ((bytesRead = inputStream.read(buffer)) != -1) {
+                    outputStream.write(buffer, 0, bytesRead);
                 }
-                Files.delete(Paths.get(filePath));
-            } catch (Exception e) {
-                log.error("getPicMediaId error", e);
             }
-            return mediaId;
-        } else {
-            try {
-                String weComAccessToken = weComAccessTokenService.getWeComAccessToken(corpId);
-                String url = String.format(POST_WE_COM_MEDIA_UPLOAD + "?access_token=%s&type=%s", weComAccessToken, "image");
-                String res = weComSendService.sendPostFile(url, cover);
-                JSONObject jsonObject = JSONObject.parseObject(res);
-                if (jsonObject != null && jsonObject.getInteger("errcode") == 0) {
-                    mediaId = jsonObject.getString("media_id");
-                    redisTemplate.opsForValue().set(key, mediaId, 2, TimeUnit.DAYS);
-                }
-            } catch (Exception e) {
-                log.error("getPicMediaId error", e);
+            inputStream.close();
+            httpUrl.disconnect();
+            File file = new File(filePath);
+            String weComAccessToken = weComAccessTokenService.getWeComAccessToken(corpId);
+            String url = String.format(POST_WE_COM_MEDIA_UPLOAD + "?access_token=%s&type=%s", weComAccessToken, "image");
+            String res;
+            if (corpId == 1L) {
+                res = httpPoolClient.post(url, file);
+            } else {
+                res = proxyHttpPoolClient.post(url, file);
             }
-            return mediaId;
+            JSONObject jsonObject = JSONObject.parseObject(res);
+            if (jsonObject != null && jsonObject.getInteger("errcode") == 0) {
+                mediaId = jsonObject.getString("media_id");
+                redisTemplate.opsForValue().set(key, mediaId, 2, TimeUnit.DAYS);
+            }
+            Files.delete(Paths.get(filePath));
+        } catch (Exception e) {
+            log.error("getPicMediaId error", e);
         }
+        return mediaId;
+
     }
 
 

+ 6 - 2
common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/MessageServiceImpl.java

@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONObject;
 import com.tzld.piaoquan.growth.common.common.base.CommonResponse;
 import com.tzld.piaoquan.growth.common.common.constant.MessageConstant;
 import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
+import com.tzld.piaoquan.growth.common.component.ProxyHttpPoolClient;
 import com.tzld.piaoquan.growth.common.dao.mapper.PreSpecialSendMessageMapper;
 import com.tzld.piaoquan.growth.common.model.bo.MsgResult;
 import com.tzld.piaoquan.growth.common.model.po.PreSpecialSendMessage;
@@ -31,6 +32,9 @@ public class MessageServiceImpl implements MessageService {
     @Autowired
     private HttpPoolClient httpPoolClient;
 
+    @Autowired
+    private ProxyHttpPoolClient proxyHttpPoolClient;
+
     @Autowired
     private WeComAccessTokenService weComAccessTokenService;
 
@@ -51,7 +55,7 @@ public class MessageServiceImpl implements MessageService {
             if (corpId == 1L) {
                 s = httpPoolClient.post(url, jsonObject.toJSONString());
             } else {
-                s = weComSendService.sendPost(url, jsonObject.toJSONString());
+                s = proxyHttpPoolClient.post(url, jsonObject.toJSONString());
             }
             JSONObject res = JSONObject.parseObject(s);
             log.info("pushWeComMessage res={}", res);
@@ -100,7 +104,7 @@ public class MessageServiceImpl implements MessageService {
             if (corpId == 1L) {
                 s = httpPoolClient.post(url, jsonObject.toJSONString());
             } else {
-                s = weComSendService.sendPost(url, jsonObject.toJSONString());
+                s = proxyHttpPoolClient.post(url, jsonObject.toJSONString());
             }
             JSONObject res = JSONObject.parseObject(s);
             log.info("sendAutoReplyMessage res={}", res);

+ 12 - 2
common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/WeComAccessTokenServiceImpl.java

@@ -2,6 +2,7 @@ package com.tzld.piaoquan.growth.common.service.Impl;
 
 import com.alibaba.fastjson.JSONObject;
 import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
+import com.tzld.piaoquan.growth.common.component.ProxyHttpPoolClient;
 import com.tzld.piaoquan.growth.common.dao.mapper.CorpMapper;
 import com.tzld.piaoquan.growth.common.model.po.Corp;
 import com.tzld.piaoquan.growth.common.model.po.CorpExample;
@@ -28,6 +29,9 @@ public class WeComAccessTokenServiceImpl implements WeComAccessTokenService {
     @Autowired
     private HttpPoolClient httpPoolClient;
 
+    @Autowired
+    private ProxyHttpPoolClient proxyHttpPoolClient;
+
     @Autowired
     private RedisTemplate<String, Object> redisTemplate;
 
@@ -52,8 +56,14 @@ public class WeComAccessTokenServiceImpl implements WeComAccessTokenService {
             Corp corp = corps.get(0);
             String cropId = corp.getCorpId();
             String secret = corp.getSecret();
-            String res = httpPoolClient.get(String.format(GET_WE_COM_ACCESS_TOKEN_URL +
-                    "?corpid=%s&corpsecret=%s", cropId, secret));
+            String res;
+            if (corpId == 1L) {
+                res = httpPoolClient.get(String.format(GET_WE_COM_ACCESS_TOKEN_URL +
+                        "?corpid=%s&corpsecret=%s", cropId, secret));
+            } else {
+                res = proxyHttpPoolClient.get(String.format(GET_WE_COM_ACCESS_TOKEN_URL +
+                        "?corpid=%s&corpsecret=%s", cropId, secret));
+            }
             JSONObject jsonObject = JSONObject.parseObject(res);
             Long expiresIn = jsonObject.getLong("expires_in");
             String newAccessToken = jsonObject.getString("access_token");

+ 5 - 1
common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/WeComUserServiceImpl.java

@@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject;
 import com.tzld.piaoquan.growth.common.common.base.CommonResponse;
 import com.tzld.piaoquan.growth.common.common.enums.PreSpecialStatusEnum;
 import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
+import com.tzld.piaoquan.growth.common.component.ProxyHttpPoolClient;
 import com.tzld.piaoquan.growth.common.dao.mapper.*;
 import com.tzld.piaoquan.growth.common.dao.mapper.ext.WeComUserMapperExt;
 import com.tzld.piaoquan.growth.common.model.bo.GroupSendWeComUserParam;
@@ -40,6 +41,9 @@ public class WeComUserServiceImpl implements WeComUserService {
     @Autowired
     private HttpPoolClient httpPoolClient;
 
+    @Autowired
+    private ProxyHttpPoolClient proxyHttpPoolClient;
+
     @Autowired
     private WeComAccessTokenService weComAccessTokenService;
 
@@ -241,7 +245,7 @@ public class WeComUserServiceImpl implements WeComUserService {
             if (corpId == 1L) {
                 res = httpPoolClient.get(url);
             } else {
-                res = weComSendService.sendGet(url);
+                res = proxyHttpPoolClient.get(url);
             }
             JSONObject jsonObject = JSONObject.parseObject(res);
             Integer errcode = jsonObject.getInteger("errcode");

+ 7 - 3
offline-module/src/main/java/com/tzld/piaoquan/offline/job/WeComHistoryDataJob.java

@@ -7,6 +7,7 @@ import com.tzld.piaoquan.growth.common.common.constant.MessageConstant;
 import com.tzld.piaoquan.growth.common.common.constant.TimeConstant;
 import com.tzld.piaoquan.growth.common.common.enums.MessageAttachmentTypeEnum;
 import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
+import com.tzld.piaoquan.growth.common.component.ProxyHttpPoolClient;
 import com.tzld.piaoquan.growth.common.dao.mapper.*;
 import com.tzld.piaoquan.growth.common.model.bo.ExternalUser;
 import com.tzld.piaoquan.growth.common.model.bo.MiniprogramRecord;
@@ -45,6 +46,9 @@ public class WeComHistoryDataJob {
     @Autowired
     private HttpPoolClient httpPoolClient;
 
+    @Autowired
+    private ProxyHttpPoolClient proxyHttpPoolClient;
+
     @Autowired
     private WeComAccessTokenService weComAccessTokenService;
 
@@ -454,7 +458,7 @@ public class WeComHistoryDataJob {
         if (corpId == 1L) {
             return httpPoolClient.post(url, param.toJSONString());
         } else {
-            return weComSendService.sendPost(url, param.toJSONString());
+            return proxyHttpPoolClient.post(url, param.toJSONString());
         }
     }
 
@@ -498,7 +502,7 @@ public class WeComHistoryDataJob {
         if (corpId == 1L) {
             return httpPoolClient.post(url, param.toJSONString());
         } else {
-            return weComSendService.sendPost(url, param.toJSONString());
+            return proxyHttpPoolClient.post(url, param.toJSONString());
         }
     }
 
@@ -635,7 +639,7 @@ public class WeComHistoryDataJob {
         if (corpId == 1L) {
             return httpPoolClient.post(url, param.toJSONString());
         } else {
-            return weComSendService.sendPost(url, param.toJSONString());
+            return proxyHttpPoolClient.post(url, param.toJSONString());
         }
     }
 

+ 5 - 1
offline-module/src/main/java/com/tzld/piaoquan/offline/job/WeComStaffDataJob.java

@@ -2,6 +2,7 @@ package com.tzld.piaoquan.offline.job;
 
 import com.alibaba.fastjson.JSONObject;
 import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
+import com.tzld.piaoquan.growth.common.component.ProxyHttpPoolClient;
 import com.tzld.piaoquan.growth.common.dao.mapper.CorpMapper;
 import com.tzld.piaoquan.growth.common.dao.mapper.StaffMapper;
 import com.tzld.piaoquan.growth.common.model.bo.XxlJobParam;
@@ -33,6 +34,9 @@ public class WeComStaffDataJob {
     @Autowired
     private HttpPoolClient httpPoolClient;
 
+    @Autowired
+    private ProxyHttpPoolClient proxyHttpPoolClient;
+
     @Autowired
     private WeComAccessTokenService weComAccessTokenService;
 
@@ -92,7 +96,7 @@ public class WeComStaffDataJob {
         if (corpId == 1L) {
             res = httpPoolClient.get(url);
         } else {
-            res = weComSendService.sendGet(url);
+            res = proxyHttpPoolClient.get(url);
         }
         log.info("getCarrierIdList corp = {}, res={}", corpId, res);
         JSONObject jsonObject = JSONObject.parseObject(res);

+ 7 - 2
offline-module/src/main/java/com/tzld/piaoquan/offline/job/WeComUserDataJob.java

@@ -3,6 +3,7 @@ package com.tzld.piaoquan.offline.job;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
+import com.tzld.piaoquan.growth.common.component.ProxyHttpPoolClient;
 import com.tzld.piaoquan.growth.common.dao.mapper.*;
 import com.tzld.piaoquan.growth.common.model.bo.XxlJobParam;
 import com.tzld.piaoquan.growth.common.model.po.*;
@@ -36,6 +37,10 @@ public class WeComUserDataJob {
     @Autowired
     private HttpPoolClient httpPoolClient;
 
+    @Autowired
+    private ProxyHttpPoolClient proxyHttpPoolClient;
+
+
     @Autowired
     private StaffMapper staffMapper;
 
@@ -188,7 +193,7 @@ public class WeComUserDataJob {
         if (corpId == 1L) {
             return httpPoolClient.post(url, param.toJSONString());
         } else {
-            return weComSendService.sendPost(url, param.toJSONString());
+            return proxyHttpPoolClient.post(url, param.toJSONString());
         }
     }
 
@@ -249,7 +254,7 @@ public class WeComUserDataJob {
         if (corpId == 1L) {
             res = httpPoolClient.get(url);
         } else {
-            res = weComSendService.sendGet(url);
+            res = proxyHttpPoolClient.get(url);
         }
         JSONObject jsonObject = JSONObject.parseObject(res);
         Integer errcode = jsonObject.getInteger("errcode");