Chapter 7. Advanced topics http://hc.apache.org/httpcomponents-client-ga/tutorial/html/advanced.html

7.3. Using the 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.

7.3.1. 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

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

7.3.2. 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.

private final class OkidokiHandler implements ResponseHandler<Boolean> {
public Boolean handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
return response.getStatusLine().getStatusCode() == 200;
}
} HttpRequestFutureTask<Boolean> 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();

7.3.3. 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.

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

7.3.4. 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

private final class MyCallback implements FutureCallback<Boolean> {

    public void failed(final Exception ex) {
// do something
} public void completed(final Boolean result) {
// do something
} public void cancelled() {
// do something
}
} HttpRequestFutureTask<Boolean> task = futureRequestExecutionService.execute(
new HttpGet("http://www.google.com"), HttpClientContext.create(),
new OkidokiHandler(), new MyCallback());

7.3.5. 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().

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 Preface http://hc.apache.org/httpcomponents-client-ga/tutorial/html/preface.html

The Hyper-Text Transfer Protocol (HTTP) is perhaps the most significant protocol used on the Internet today. Web services, network-enabled appliances and the growth of network computing continue to expand the role of the HTTP protocol beyond user-driven web browsers, while increasing the number of applications that require HTTP support.

Although the java.net package provides basic functionality for accessing resources via HTTP, it doesn't provide the full flexibility or functionality needed by many applications. HttpClient seeks to fill this void by providing an efficient, up-to-date, and feature-rich package implementing the client side of the most recent HTTP standards and recommendations.

Designed for extension while providing robust support for the base HTTP protocol, HttpClient may be of interest to anyone building HTTP-aware client applications such as web browsers, web service clients, or systems that leverage or extend the HTTP protocol for distributed communication.

1. HttpClient scope

  • Client-side HTTP transport library based on HttpCore

  • Based on classic (blocking) I/O

  • Content agnostic

2. What HttpClient is NOT

  • HttpClient is NOT a browser. It is a client side HTTP transport library. HttpClient's purpose is to transmit and receive HTTP messages. HttpClient will not attempt to process content, execute javascript embedded in HTML pages, try to guess content type, if not explicitly set, or reformat request / rewrite location URIs, or other functionality unrelated to the HTTP transport.

Apache HttpComponents – HttpComponents HttpAsyncClient Examples http://hc.apache.org/httpcomponents-asyncclient-dev/examples.html

http://hc.apache.org/httpcomponents-asyncclient-dev/httpasyncclient/examples/org/apache/http/examples/nio/client/AsyncClientHttpExchange.java http://hc.apache.org/httpcomponents-asyncclient-dev/httpasyncclient/examples/org/apache/http/examples/nio/client/AsyncClientHttpExchange.java

package org.apache.http.examples.nio.client;

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; /**
* This example demonstrates a basic asynchronous HTTP request / response exchange.
* Response content is buffered in memory for simplicity.
*/
public class AsyncClientHttpExchange { public static void main(final String[] args) throws Exception {
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
try {
httpclient.start();
HttpGet request = new HttpGet("http://httpbin.org/get");
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");
} }
Apache HttpComponents – Apache HttpComponents http://hc.apache.org/

HttpComponents AsyncClient

Asynch HttpClient is a HTTP/1.1 compliant HTTP agent implementation based on HttpCore NIO and HttpClient components. It is a complementary module to Apache HttpClient intended for special cases where ability to handle a great number of concurrent connections is more important than performance in terms of a raw data throughput.

【nio与性能的关系】

Using the FutureRequestExecutionService Based on classic (blocking) I/O handle a great number of concurrent connections is more important than performance in terms of a raw data throughput的更多相关文章

  1. Jakarta Commons Cookbook

      Cookbook就是工具书,应该是前年看的,在中关村看的影印版,全英文,本书主要讲解了一下模块: Core:BeanUtils,Lang,Collections,logging Db:DbUtil ...

  2. java_软件发布版本_Asynch HttpClien 对比发行版本说明_Alpha、Beta、RC、GA版本的区别

    今天看了一天的apache 的httpasyncclient ,为了和默认的httpclient做个对比,httpcore是核心轻量级的提供传统阻塞IO 和 java NIO两种方式,httpclie ...

  3. Java性能提示(全)

    http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...

  4. System Error Codes

    很明显,以下的文字来自微软MSDN 链接http://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx M ...

  5. 转:一个C语言实现的类似协程库(StateThreads)

    http://blog.csdn.net/win_lin/article/details/8242653 译文在后面. State Threads for Internet Applications ...

  6. nginx---reference

    nginx (pronounced "engine x") is a free open source web server written by Igor Sysoev, a R ...

  7. Data Center手册(4):设计

    基础架构 拓扑图 Switching Path L3 routing at aggregation layer L2 switching at access layer L3 switch融合了三种功 ...

  8. HTTP/1.0 vs HTTP/1.1 vs HTTP/2

    HTTP 1.0 vs 1.1 Proxy support and the Host field: HTTP 1.1 has a required Host header by spec. HTTP ...

  9. state Threads 开源库介绍

    译文在后面. State Threads for Internet Applications Introduction State Threads is an application library ...

随机推荐

  1. JS 利用正则表达式替换字符串

    JS 利用正则表达式替换字符串 博客分类: JavaScript 学习资料 Java代码 收藏代码 JS 利用正则表达式替换字符串 var data = "123123,213,12312, ...

  2. js 实现依赖注入的思想,后端框架思想搬到前端来

    前述:咱们写一些页面的时候,很多需要用ajax来实现,显示又有很多表单提交的add或者update操作,太烦了,能不能有什么方法能够简单些呢? 说实话我都是被公司给逼的 应用场景: 前后端一一对应.表 ...

  3. maven中配置jdk版本

    1 maven 中配置 <build> <plugins> <plugin> <groupId>org.apache.maven.plugins< ...

  4. C++中常函数内部的this指针也是const类型的

    代码中碰到一个奇怪的现象,在同样的函数中调用this指针,结果却有一个无法通过编译 // 读取连接信息 void ThirdWizardPage::ReadConnection() { QFile f ...

  5. 解决将Ubuntu下导出的requirements.txt到Centos服务器上面出现pkg-resource的版本为0.0.0

    最直接有效的方法: 原因:

  6. android 获取屏幕高度和宽度 的方法

    我们需要获取Android手机或Pad的屏幕的物理尺寸,以便于界面的设计或是其他功能的实现.下面就介绍讲一讲如何获取屏幕的物理尺寸 下面的代码即可获取屏幕的尺寸.    在一个Activity的onC ...

  7. js数组最大值和最小值计算

    基本概念 reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值. reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被 ...

  8. Python教程:[43]Word基本操作

    使用python操作Word用到了win32com模块,我们现在就要介绍一下python对Word的基本操作,文章涉及到如何与Word程序建立连接.如果与Word文档建立连接的,以及对Word文档的基 ...

  9. SDRAM基础

    一. 介绍 存储器的最初结构为线性,它在任何时刻,地址线中都只能有一位有效.设容量为N×M的存储器有S0-Sn-1条地址线:当容量增大时,地址选择线的条数也要线性增多,利用地址译码虽然可有效地减少地址 ...

  10. setTranslatesAutoresizingMaskIntoConstraints和setFrame组合使用导致的异常

    在用Ojbect-c开发OSX应用的时候需要用到自定义控件并用代码进行布局,很自然地就使用了setTranslatesAutoresizingMaskIntoConstraints和setFrame组 ...