Prechádzať zdrojové kódy

RestTemplate http 连接池,异常处理

wks 3 rokov pred
rodič
commit
b02b2bf0fd

+ 0 - 5
src/main/java/com/ydtech/config/MvcConfig.java

@@ -102,11 +102,6 @@ public class MvcConfig implements WebMvcConfigurer {
         registry.addResourceHandler(uploadFileUrl + "**").addResourceLocations("file:" + uploadFilePath);
     }
 
-    @Bean
-    public RestTemplate restTemplate() {
-        return new RestTemplate();
-    }
-
     @Bean
     public WxMpDefaultConfigImpl wxMpDefaultConfig() {
         WxMpDefaultConfigImpl wxMpDefaultConfig = new WxMpDefaultConfigImpl();

+ 23 - 0
src/main/java/com/ydtech/config/resttemplate/CustomResponseErrorHandler.java

@@ -0,0 +1,23 @@
+package com.ydtech.config.resttemplate;
+
+import com.ydtech.exception.SystemException;
+import org.springframework.http.client.ClientHttpResponse;
+import org.springframework.web.client.ResponseErrorHandler;
+
+import java.io.IOException;
+
+public class CustomResponseErrorHandler implements ResponseErrorHandler {
+
+    @Override
+    public boolean hasError(ClientHttpResponse response) throws IOException {
+        int rawStatusCode = response.getRawStatusCode();
+        return rawStatusCode > 200;
+    }
+
+    // 处理错误
+    @Override
+    public void handleError(ClientHttpResponse response) throws IOException {
+        throw new SystemException("请求异常" + response.getStatusText());
+    }
+
+}

+ 52 - 0
src/main/java/com/ydtech/config/resttemplate/RestTemplateConfig.java

@@ -0,0 +1,52 @@
+package com.ydtech.config.resttemplate;
+
+
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.conn.socket.ConnectionSocketFactory;
+import org.apache.http.conn.socket.PlainConnectionSocketFactory;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.client.ClientHttpRequestFactory;
+import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
+import org.springframework.web.client.RestTemplate;
+
+import java.util.Collections;
+
+@Configuration
+public class RestTemplateConfig {
+    @Bean
+    public RestTemplate restTemplate() {
+        RestTemplate restTemplate = new RestTemplate(httpRequestFactory());
+        restTemplate.setErrorHandler(new CustomResponseErrorHandler());
+        restTemplate.setInterceptors(Collections.singletonList(new RestTemplateRequestInterceptor()));
+        return restTemplate;
+    }
+
+    @Bean
+    public ClientHttpRequestFactory httpRequestFactory() {
+        return new HttpComponentsClientHttpRequestFactory(httpClient());
+    }
+
+    @Bean
+    public HttpClient httpClient() {
+        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
+        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
+        //设置整个连接池最大连接数
+        connectionManager.setMaxTotal(400);
+
+        //路由是对maxTotal的细分
+        connectionManager.setDefaultMaxPerRoute(100);
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setSocketTimeout(30000)  //返回数据的超时时间
+                .setConnectTimeout(10000) //连接上服务器的超时时间
+                .setConnectionRequestTimeout(1000) //从连接池中获取连接的超时时间
+                .build();
+        return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager).build();
+    }
+}

+ 33 - 0
src/main/java/com/ydtech/config/resttemplate/RestTemplateRequestInterceptor.java

@@ -0,0 +1,33 @@
+package com.ydtech.config.resttemplate;
+
+import com.ydtech.exception.SystemException;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.HttpRequest;
+import org.springframework.http.client.ClientHttpRequestExecution;
+import org.springframework.http.client.ClientHttpRequestInterceptor;
+import org.springframework.http.client.ClientHttpResponse;
+
+import java.io.IOException;
+import java.net.SocketTimeoutException;
+
+@Slf4j
+public class RestTemplateRequestInterceptor implements ClientHttpRequestInterceptor {
+
+    @Override
+    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
+        ClientHttpResponse execute;
+        try {
+            execute = execution.execute(request, body);
+        } catch (IOException e) {
+            log.info("appRestTemplate...error:" + e);
+            // 特殊处理超时异常
+            if (e instanceof SocketTimeoutException) {
+                // 返回自定义异常
+                throw new SystemException("请求超时请重试");
+            }
+            throw e;
+        }
+        return execute;
+    }
+
+}