zoukankan      html  css  js  c++  java
  • 使用PoolingHttpClientConnectionManager解决httpclient的多线程请求问题

    直接上代码

    1.主程序

    public class TestMain {
    
        public static void main(String[] args) throws NSQException, TimeoutException {
            ExecutorService pool = Executors.newCachedThreadPool();
            // http请求
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setDefaultMaxPerRoute(800);// 设置每个路由基础的连接
            cm.setMaxTotal(1000);//设置最大连接数//cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute);// 设置目标主机的最大连接数
            CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
            for (int i = 0; i < 1000; i++) {
                TestRunnable tmp = new TestRunnable(httpClient);
                new Thread(tmp).start();
            }
            
        }
    }

    2.线程使用httpclient进行post请求,其中调用的post请求具体实现已经做了封装,可参考我之前的文章

    class TestRunnable implements Runnable {
        private final CloseableHttpClient httpclient;
    
        public TestRunnable(CloseableHttpClient httpClient) {
            this.httpclient = httpClient;
        }
    
        @Override
        public void run() {
            String id = "444";
            String name = "testName";
            Map<String, String> param = new HashMap<String, String>();
            param.put("id", id);
            param.put("name", name);
    
            String result = HttpClientUtil.doHttpPost("http://ip:port/testapi", param,httpclient);
            System.out.println(result);
        }
        
    }
  • 相关阅读:
    遗产
    (OK) C/S—心跳检测—heartbeat
    如何判断SOCKET已经断开
    accept() returns the same socket descriptor
    C/S—心跳检测—heartbeat
    Linux—Network—Socket—Programming—heartbeat—源代码
    CentOS 7
    yum—repo—yum源
    (OK) CentOS7—mp4—avi—视频播放—SMPlayer
    读史
  • 原文地址:https://www.cnblogs.com/JoeyWong/p/9056346.html
Copyright © 2011-2022 走看看