我正在测试一个多线程代码,该代码使用CloseableHttpAsyncClient客户端发送一组http请求(请参阅下面的代码片段(。
我正在获得以下输出:
Failed ->java.io.IOException: Connection reset by peer-null
Failed ->org.apache.http.ConnectionClosedException: Connection closed-null
Thread: 0-Time: 2955ms-Completed: 1000-Failed: 0-Cancelled: 0- Countdown: 0
Thread: 1-Time: 2855ms-Completed: 999-Failed: 0-Cancelled: 0-Countdown: 0
Thread: 2-Time: 2741ms-Completed: 999-Failed: 1-Cancelled: 0-Countdown: 0
Thread: 3-Time: 2678ms-Completed: 999-Failed: 1-Cancelled: 0-Countdown: 0
Thread: 4-Time: 2654ms-Completed: 1000-Failed: 0-Cancelled: 0-Countdown: 0
因此,其中两个线程正确执行了所有1000个请求,另外两个线程出现了连接错误,这些错误被正确捕获,其中一个线程(编号1(完成了999个请求,没有收到任何失败或取消的通知。
我的问题是:
失败的方法中有没有任何方法可以理解哪一个是失败的请求,这样我就可以进行后处理来重新发送那些失败的请求?
为什么在没有失败、取消或异常的情况下,倒计时的次数会达到0,而不是所有的请求都完成了?
class AsynchThread extends Thread{ CloseableHttpAsyncClient httpclient; int n; int ncompleted =0; int nfailed =0; int ncancelled =0; long time; CountDownLatch latch; public AsynchThread(CloseableHttpAsyncClient httpclient, int n) throws IOReactorException { this.jobs = jobs; this.httpclient = httpclient; this.n = n; } public void process() throws InterruptedException, IOException { latch = new CountDownLatch(n); long starttime = System.currentTimeMillis(); for (int v=0;v<n; v++) { HttpPost httppost = ... httpclient.execute(httppost, new FutureCallback<HttpResponse>() { public void completed(final HttpResponse response) { latch.countDown(); ncompleted += 1; } public void failed(final Exception ex) { latch.countDown(); nfailed += 1; System.out.println("Failed ->" + ex); } public void cancelled() { latch.countDown(); ncancelled += 1; System.out.println("Cancelled ->" + ex); } }); } latch.await(); time = System.currentTimeMillis()-starttime; } public void run() { try { process(); }catch(Exception e) { System.out.println(e.getStackTrace()); } } } public static void main(final String[] args) throws Exception { CloseableHttpAsyncClient httpclient = ... int n = 5; int nprocthread = 1000; AsynchThread[] threads = new AsynchThread[n]; for (int i=0; i<n; i++) { threads[i] = acall.createThread(httpclient, nprocthread); threads[i].run(); } for(int i = 0; i < threads.length; i++) threads[i].join(); for(int i = 0; i < threads.length; i++) { System.out.println("Thread: " + i + "-Time: " + threads[i].time + "ms-Completed: " + threads[i].ncompleted + "-Failed: " + threads[i].nfailed + "-Cancelled: " + threads[i].ncancelled + "-Countdown: " + threads[i].latch.getCount()); } }
非常感谢。
添加标题"连接:关闭"时,所有问题都得到了解决