1. 程式人生 > >Java異步執行多個HTTP請求的例子(需要apache http類庫)

Java異步執行多個HTTP請求的例子(需要apache http類庫)

ride 同步 conn done 例子 latch block org ftw

直接上代碼

package org.jivesoftware.spark.util;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.jivesoftware.DebugPrint;
import org.jivesoftware.spark.SparkManager;

//異步埋點數據采集工具類
public class HotClickAsync {
    static ExecutorService service = Executors.newSingleThreadExecutor(); //單一線程
    // 調用http請求。不阻塞主線程
    public static void SendRequest(final String event)
            throws InterruptedException, IOException {
        
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    SendRequestAsync(event,SparkManager.getSessionManager().getUsername());
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        service.execute(run);
    }

    // 阻塞HTTP調用
    private static void SendRequestAsync(String event,String username)
            throws InterruptedException, IOException {
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(1000) // http超時
                .setConnectTimeout(1000).build(); // 連接超時
        CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
                .setDefaultRequestConfig(requestConfig).build();
        try {
            httpclient.start();
            final HttpGet[] requests = new HttpGet[] { new HttpGet(
                    "http://XXXXXX.cn:81/HotClick.aspx?event="+ event +"&username="+username) // 第一個采集地址
            // , new HttpGet("http://mta.qq.com")//第二個采集地址, http://mta.qq.com/
            };
            // 同步計數
            final CountDownLatch latch = new CountDownLatch(requests.length);
            for (final HttpGet request : requests) {
                httpclient.execute(request, new FutureCallback<HttpResponse>() {

                    @Override
                    public void completed(final HttpResponse response) {
                        latch.countDown();
                        DebugPrint.outStirng(request.getRequestLine() + "####->"
                                + response.getStatusLine());
                        
                    }

                    @Override
                    public void failed(final Exception ex) {
                        latch.countDown();
                        DebugPrint.outStirng(request.getRequestLine() + "####->" + ex);
                    }

                    @Override
                    public void cancelled() {
                        latch.countDown();
                        //DebugPrint.outStirng(request.getRequestLine()
                        //        + " cancelled");
                    }

                });
            }
            latch.await();
        } finally {
            httpclient.close();
        }
        DebugPrint.outStirng(" ###  HotClickAsync Done ###");

    }

}

Java異步執行多個HTTP請求的例子(需要apache http類庫)