jjzjj

java - HTTPClient 4.x 连接重用没有发生

coder 2024-03-27 原文

我尝试了以下 Apache http 客户端示例:

http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientMultiThreadedExecution.java

我将最大池大小设置为 5 并运行十个线程。运行此代码后,当我检查 netstat 时,我看到有 10 个 TCP 连接处于打开状态。我期待这些连接被重用。为什么是这样 ?我错过了什么吗?

代码片段如下:

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

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(
    new Scheme("http", 18080, PlainSocketFactory.getSocketFactory()));

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    cm.setDefaultMaxPerRoute(5);
    cm.setMaxTotal(5);


    HttpClient httpclient = new DefaultHttpClient(cm);
    try {
        // create an array of URIs to perform GETs on
        String uri = "http://test.webservice.com:18080/TestServlet";
        String data = "This is a test message";

        System.out.println("Started at: " + new Date());
        // creating 10 threads
        PostThread[] threads = new PostThread[10];

        for (int i = 0; i < threads.length; i++) {
        HttpPost httpPost = new HttpPost(uri);
        threads[i] = new PostThread(httpclient, httpPost, data, i + 1);
            threads[i].start();
            //Thread.sleep(1000);
        }

       // join the threads
        for (int j = 0; j < threads.length; j++) {
            threads[j].join();
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        System.out.println("Ended at: " + new Date());
        httpclient.getConnectionManager().shutdown();
    }
}

/**
 * A thread that performs a POST.
 */
static class PostThread extends Thread {

    private final HttpClient httpClient;
    private final HttpContext context;
    private final HttpPost httpPost;
    private final int id;
    private final String data;

    public PostThread(HttpClient httpClient, HttpPost httpPost, String data, int id) {
        this.httpClient = httpClient;
        this.context = new BasicHttpContext();
        this.httpPost = httpPost;
        this.id = id;
        this.data = data;
    }

    /**
     * Executes the PostMethod and prints some status information.
     */
    @Override
    public void run() {

        //System.out.println(id + " - about to get something from " + httpPost.getURI());

        try {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("XML",data));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));

            // execute the method
            HttpResponse response = httpClient.execute(httpPost, context);

            //System.out.println(id + " - get executed");
            // get the response body as an array of bytes
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
                System.out.println("Success");

            //Is this step necessary ?? Need to check as only status code is required
            //httpPost.abort();
            //HttpEntity entity = response.getEntity();

            //And this ?
            //EntityUtils.consume(entity);

        } catch (Exception e) {
            httpPost.abort();
            System.out.println(id + " - error: " + e);
        }
    }

}}

最佳答案


        //Is this step necessary ?? Need to check as only status code is required
        //httpPost.abort();
        //HttpEntity entity = response.getEntity();

        //And this ?
        //EntityUtils.consume(entity);

你猜怎么着?是的。

一个必须确保响应内容被消费,以便将底层连接释放回连接管理器。调用 EntityUtils#consumehttpUriRequest#abort 触发连接释放回池。不同之处在于前者试图保持连接,而后者则不会。

关于java - HTTPClient 4.x 连接重用没有发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8200038/

有关java - HTTPClient 4.x 连接重用没有发生的更多相关文章

  1. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  2. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  3. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  4. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  5. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  6. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  7. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  8. 没有类的 Ruby 方法? - 2

    大家好!我想知道Ruby中未使用语法ClassName.method_name调用的方法是如何工作的。我头脑中的一些是puts、print、gets、chomp。可以在不使用点运算符的情况下调用这些方法。为什么是这样?他们来自哪里?我怎样才能看到这些方法的完整列表? 最佳答案 Kernel中的所有方法都可用于Object类的所有对象或从Object派生的任何类。您可以使用Kernel.instance_methods列出它们。 关于没有类的Ruby方法?,我们在StackOverflow

  9. ruby-on-rails - Rails 3,嵌套资源,没有路由匹配 [PUT] - 2

    我真的为这个而疯狂。我一直在搜索答案并尝试我找到的所有内容,包括相关问题和stackoverflow上的答案,但仍然无法正常工作。我正在使用嵌套资源,但无法使表单正常工作。我总是遇到错误,例如没有路线匹配[PUT]"/galleries/1/photos"表格在这里:/galleries/1/photos/1/edit路线.rbresources:galleriesdoresources:photosendresources:galleriesresources:photos照片Controller.rbdefnew@gallery=Gallery.find(params[:galle

  10. ruby-on-rails - 有没有办法为 CarrierWave/Fog 设置上传进度指示器? - 2

    我在Rails应用程序中使用CarrierWave/Fog将视频上传到AmazonS3。有没有办法判断上传的进度,让我可以显示上传进度如何? 最佳答案 CarrierWave和Fog本身没有这种功能;你需要一个前端uploader来显示进度。当我不得不解决这个问题时,我使用了jQueryfileupload因为我的堆栈中已经有jQuery。甚至还有apostonCarrierWaveintegration因此您只需按照那里的说明操作即可获得适用于您的应用的进度条。 关于ruby-on-r

随机推荐