有個需求要在 SpringMVC 的 mapping URL 跳轉前完成一項統計業務。這種情境顯然必須非同步處理,否則一旦出錯或拋異常,就會拖累後面的網頁跳轉。非同步的本質是非阻塞:無論呼叫成功與否,程式都會立刻往下執行,不必等 I/O 處理完畢才返回。
httpasyncclient-4.0.1.jar、httpclient-4.3.2.jar、httpcore-4.3.2.jar、httpcore-nio-4.3.2.jar、commons-logging-1.1.3.jar。
java.util.concurrent 主要包含三類工具:Executor Framework、並發集合(Concurrent Collection)與同步器(Synchronizer)。Future 介面表示非同步計算的結果,提供檢查計算是否完成、等待完成並取得結果的方法。計算完成後只能用 get 取值,必要時會阻塞;cancel 則用於取消。一旦計算完成就不能再取消。
import java.util.concurrent.Future;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
/**
* 基本的非同步 HTTP 請求/回應交換示範。
*/
public class AsyncClientHttpExchange {
public static void main(final String[] args) throws Exception {
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
try {
httpclient.start();
HttpGet request = new HttpGet("https://www.apache.org/");
Future<HttpResponse> future = httpclient.execute(request, null);
HttpResponse response = future.get(); // 取得結果
System.out.println("Response: " + response.getStatusLine());
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
}
}
同步器是讓線程能等待另一個線程的物件,最常用的是 CountDownLatch 與 Semaphore,較少用的是 CyclicBarrier 與 Exchanger。Semaphore 是計數信號量,維護一個許可集,acquire() 在許可可用前會阻塞,release() 則新增一個許可。CountDownLatch 是一次性的障礙:以給定的計數初始化,await() 會在計數歸零前持續阻塞,之後所有等待線程被釋放;這種現象只發生一次,計數無法重置(需要重置時請改用 CyclicBarrier)。
import java.util.concurrent.CountDownLatch;
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;
/**
* 完全非同步地執行多組 HTTP 交換,
* 個別操作的結果透過 callback 介面回報。
*/
public class AsyncClientHttpExchangeFutureCallback {
public static void main(final String[] args) throws Exception {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(3000).setConnectTimeout(3000).build();
CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
.setDefaultRequestConfig(requestConfig).build();
try {
httpclient.start();
final HttpGet[] requests = new HttpGet[] {
new HttpGet("https://www.apache.org/"),
new HttpGet("https://www.verisign.com/"),
new HttpGet("https://www.google.com/"),
new HttpGet("https://www.baidu.com/") };
final CountDownLatch latch = new CountDownLatch(requests.length);
for (final HttpGet request : requests) {
httpclient.execute(request, new FutureCallback<HttpResponse>() {
// 無論完成還是失敗都呼叫 countDown()
@Override
public void completed(final HttpResponse response) {
latch.countDown();
System.out.println(request.getRequestLine() + "->"
+ response.getStatusLine());
}
@Override
public void failed(final Exception ex) {
latch.countDown();
System.out.println(request.getRequestLine() + "->" + ex);
}
@Override
public void cancelled() {
latch.countDown();
System.out.println(request.getRequestLine() + " cancelled");
}
});
}
latch.await();
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
}
}
三個 callback(completed / failed / cancelled)都必須呼叫 countDown(),否則 latch.await() 會永遠等下去——這是使用非同步客戶端最常見的 bug。另外別忘了 httpclient.close(),並務必設定連線與讀取逾時,避免請求卡死。
參考文檔:https://hc.apache.org/httpcomponents-asyncclient-dev/examples.html
相關閱讀: