使用FutureRequestExecutionService

官網地址

http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/advanced.html#d5e949

1.使用FutureRequestExecutionService

Using the FutureRequestExecutionService, you can schedule http calls and treat the response as a Future. This is useful when e.g. making multiple calls to a web service. The advantage of using the FutureRequestExecutionService is that you can use multiple threads to schedule requests concurrently, set timeouts on the tasks, or cancel them when a response is no longer necessary.

FutureRequestExecutionService wraps the request with a HttpRequestFutureTask, which extends FutureTask. This class allows you to cancel the task as well as keep track of various metrics such as request duration.

使用FutureRequestExecutionService,你可以使用異步的方式調用http。當例如多次調用Web服務時,此功能很有用。使用FutureRequestExecutionService的優勢在於,您可以使用多個線程來同時調度請求,設置任務超時或在不再需要響應時取消它們。

FutureRequestExecutionService使用HttpRequestFutureTask包裝請求,該請求擴展了FutureTask。該類使您可以取消任務以及跟蹤各種度量標準,例如請求持續時間。

2. Creating the FutureRequestExecutionService

The constructor for the futureRequestExecutionService takes any existing httpClient instance and an ExecutorService instance. When configuring both, it is important to align the maximum number of connections with the number of threads you are going to use. When there are more threads than connections, the connections may start timing out because there are no available connections. When there are more connections than threads, the futureRequestExecutionService will not use all of them

futureRequestExecutionService的構造函數採用任何現有的httpClient實例和一個ExecutorService實例。同時配置兩者時,重要的是將最大連接數與要使用的線程數對齊。當線程數超過連接數時,由於沒有可用的連接,連接可能開始超時。當連接數多於線程數時,futureRequestExecutionService將不會全部使用它們

HttpClient httpClient = HttpClientBuilder.create().setMaxConnPerRoute(5).build();
ExecutorService executorService = Executors.newFixedThreadPool(5);
FutureRequestExecutionService futureRequestExecutionService =
new FutureRequestExecutionService(httpClient, executorService);

3.Scheduling requests

To schedule a request, simply provide a HttpUriRequest, HttpContext, and a ResponseHandler. Because the request is processed by the executor service, a ResponseHandler is mandatory.

要計劃一個請求,只需提供一個HttpUriRequest,HttpContext和ResponseHandler。由於請求是由執行者服務處理的,因此ResponseHandler是必需的。

private final class OkidokiHandler implements ResponseHandler {
public Boolean handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
return response.getStatusLine().getStatusCode() == 200;
}
}

HttpRequestFutureTask task = futureRequestExecutionService.execute(
new HttpGet(“http://www.google.com”), HttpClientContext.create(),
new OkidokiHandler());
// blocks until the request complete and then returns true if you can connect to Google
boolean ok=task.get();

4.Canceling tasks

Scheduled tasks may be cancelled. If the task is not yet executing but merely queued for execution, it simply will never execute. If it is executing and the mayInterruptIfRunning parameter is set to true, abort() will be called on the request; otherwise the response will simply be ignored but the request will be allowed to complete normally. Any subsequent calls to task.get() will fail with an IllegalStateException. It should be noticed that canceling tasks merely frees up the client side resources. The request may actually be handled normally on the server side.

調度的任務可能會被取消。如果任務尚未執行而僅排隊等待執行,則它將永遠不會執行。如果正在執行,並且mayInterruptIfRunning參數設置爲true,則將在請求上調用abort();否則,將取消調用。否則,將僅忽略響應,但將允許請求正常完成。隨後對task.get()的任何調用都將失敗,並出現IllegalStateException。應當注意,取消任務僅釋放客戶端資源。該請求實際上可以在服務器端正常處理。

task.cancel(true)
task.get() // throws an Exception

5.Callbacks

Instead of manually calling task.get(), you can also use a FutureCallback instance that gets callbacks when the request completes. This is the same interface as is used in HttpAsyncClient

除了手動調用task.get()之外,還可以使用FutureCallback實例,該實例在請求完成時獲取回調。這與HttpAsyncClient中使用的接口相同

private final class MyCallback implements FutureCallback {

public void failed(final Exception ex) {
    // do something
}

public void completed(final Boolean result) {
    // do something
}

public void cancelled() {
    // do something
}

}

HttpRequestFutureTask task = futureRequestExecutionService.execute(
new HttpGet(“http://www.google.com”), HttpClientContext.create(),
new OkidokiHandler(), new MyCallback());

6 Metrics

FutureRequestExecutionService is typically used in applications that make large amounts of web service calls. To facilitate e.g. monitoring or configuration tuning, the FutureRequestExecutionService keeps track of several metrics.

Each HttpRequestFutureTask provides methods to get the time the task was scheduled, started, and ended. Additionally, request and task duration are available as well. These metrics are aggregated in the FutureRequestExecutionService in a FutureRequestExecutionMetrics instance that may be accessed through FutureRequestExecutionService.metrics().

FutureRequestExecutionService通常用於進行大量Web服務調用的應用程序中。爲了方便進行監視或配置調整,FutureRequestExecutionService會跟蹤幾個指標。

每個HttpRequestFutureTask提供的方法都可以獲取計劃,開始和結束任務的時間。此外,請求和任務持續時間也可用。這些指標彙總在FutureRequestExecutionMetrics實例的FutureRequestExecutionService中,可以通過FutureRequestExecutionService.metrics()訪問該實例。

task.scheduledTime() // returns the timestamp the task was scheduled
task.startedTime() // returns the timestamp when the task was started
task.endedTime() // returns the timestamp when the task was done executing
task.requestDuration // returns the duration of the http request
task.taskDuration // returns the duration of the task from the moment it was scheduled

FutureRequestExecutionMetrics metrics = futureRequestExecutionService.metrics()
metrics.getActiveConnectionCount() // currently active connections
metrics.getScheduledConnectionCount(); // currently scheduled connections
metrics.getSuccessfulConnectionCount(); // total number of successful requests
metrics.getSuccessfulConnectionAverageDuration(); // average request duration
metrics.getFailedConnectionCount(); // total number of failed tasks
metrics.getFailedConnectionAverageDuration(); // average duration of failed tasks
metrics.getTaskCount(); // total number of tasks scheduled
metrics.getRequestCount(); // total number of requests
metrics.getRequestAverageDuration(); // average request duration
metrics.getTaskAverageDuration(); // average task duration

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章