HttpClient高并发内存溢出

apache 的HttpClient很强大,据说可以承受一万左右的高并发,但是在做项目的时候用HttpClient进行附件上传,并发1000不到的时候都导致了内存溢出,核心代码为:

HttpPost post = new HttpPost(url.toString()); post.setEntity(multipartEntityBuilder.build());

HttpResponse response = httpClient.execute(post);

经过调试和查看httpClient的源码发现,由于httpClient.execute(post)返回值response并不能close,因此在上传大文件而且高并发的情况下会导致线程一直被占用,导致资源不足

用CloseableHttpClient来替代HttpClient,httpClient.execute(post)得到CloseableHttpResponse可以被关闭,从而避免了上述问题

  HttpPost post = new HttpPost(url.toString());
        post.setEntity(multipartEntityBuilder.build());
        // try with resource语法response.close()会被自动调用
        try (CloseableHttpResponse response = httpClient.execute(post)) { 

        } catch (Exception ex) {

        } finally {

        }

你可能感兴趣的:(java)