packageorg.jivesoftware.spark.util;importjava.io.IOException;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importorg.apache.http.HttpResponse;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.concurrent.FutureCallback;importorg.apache.http.impl.nio.client.CloseableHttpAsyncClient;importorg.apache.http.impl.nio.client.HttpAsyncClients;importorg.jivesoftware.DebugPrint;importorg.jivesoftware.spark.SparkManager;//异步埋点数据采集工具类
public classHotClickAsync {static ExecutorService service = Executors.newSingleThreadExecutor(); //单一线程//调用http请求。不阻塞主线程
public static void SendRequest(finalString event)throwsInterruptedException, IOException {
Runnable run= newRunnable() {
@Overridepublic voidrun() {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 voidSendRequestAsync(String event,String username)throwsInterruptedException, 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[] { newHttpGet("http://XXXXXX.cn:81/HotClick.aspx?event="+ event +"&username="+username) //第一个采集地址//, new HttpGet("http://mta.qq.com")//第二个采集地址,http://mta.qq.com/
};//同步计数
final CountDownLatch latch = newCountDownLatch(requests.length);for (finalHttpGet request : requests) {
httpclient.execute(request,new FutureCallback() {
@Overridepublic void completed(finalHttpResponse response) {
latch.countDown();
DebugPrint.outStirng(request.getRequestLine()+ "####->"
+response.getStatusLine());
}
@Overridepublic void failed(finalException ex) {
latch.countDown();
DebugPrint.outStirng(request.getRequestLine()+ "####->" +ex);
}
@Overridepublic voidcancelled() {
latch.countDown();//DebugPrint.outStirng(request.getRequestLine()//+ " cancelled");
}
});
}
latch.await();
}finally{
httpclient.close();
}
DebugPrint.outStirng(" ### HotClickAsync Done ###");
}
}