在JavaMain中正常,在tomcat上非常慢

dpiehjr4  于 2021-10-10  发布在  Java
关注(0)|答案(0)|浏览(244)

我发现这段代码在一个独立的java应用程序(runnable jar)上运行,而在tomcat(8)上部署war时速度非常慢,我找不到原因。runnable jar使用与war相同的ApacheHTTP客户端库和相同的java版本(8)。我注意到服务器没有返回“content-length”响应头,而是使用了“chunked-encoding”特性。我启用了http wire日志记录,发现在“tomcat”案例中,响应主体(响应总大小约为2mb)到达,但速度非常慢(超过4分钟),而在独立案例中,所有响应在几秒钟内到达。

public static void main(String[] args) throws Exception {

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .setSocketTimeout(10000)
                .build();

        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy).build();

        CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext)
                .setSSLHostnameVerifier(getHostnameVerifier()).setDefaultRequestConfig(requestConfig).build();

     try {
            HttpGet req = new HttpGet("https://someurl");
            ((HttpGet) req).setHeader("Accept", "*/*");
            ((HttpGet) req).setHeader("Content-Type", "application/json");

            HttpResponse httpResponse = httpClient.execute(req);

            if ((httpResponse != null) && (httpResponse.getStatusLine() != null)
                    && (httpResponse.getStatusLine().getStatusCode() == 200)) {
                System.out.println(EntityUtils.toString(httpResponse.getEntity()));
            }

     } catch (Exception e) {
         System.out.println("Exception" + e);
     }
 }

更新:使用另一个http客户端(okhttp),我遇到了同样的“问题”,在tomcat上,我在4分钟后得到了响应;现在我想这是和tomcat有关的。。。疯子

OkHttpClient client = getUnsafeOkHttpClient();

     Request request = new Request.Builder().url("https://someurl").build();

        String body = null;
        logger.info("HTTP REQUEST BEGIN");
        try (Response response = client.newCall(request).execute()) {
            logger.info("HTTP REQUEST END");
            body = response.body().string(); // here waits a lot...
        } catch (Exception e) {
                      logger.info("exception=" + e);
        }                   
        logger.info("response=" + body);

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题