使用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);
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM