Java uses httpasyncclient for asynchronous HTTP requests
Some time ago there was a need to complete a statistical business before SPRINGMVC mapping's URL jump. There is a clear need for asynchronous processing, or an error or exception will affect the subsequent page jumps. The asynchronous way is also non-blocking, when the asynchronous call succeeds or not, the program goes down and does not have to wait until the input and output processing is finished before returning.
Mainly used in the 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 includes three types of tools, Executor freamework, concurrent collections (Concurrent Collection), and Synchronizer (Synchronizer). The following example uses Java.util.concurrent.Future to request only one URL for an asynchronous request. The future interface represents the result of an asynchronous calculation. It provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to get the results of the calculation. You can only use the Get method to get the results after the calculation is complete and, if necessary, block this method before the calculation is complete. Cancellation is performed by the Cancel method. Other methods are provided to determine whether the task is completed properly or canceled. Once the calculation is complete, you can no longer cancel the calculation. If you use the future for the sake of cancellation and do not provide the available results, you can declare the Future<?> form type and return null as the result of the underlying task.
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 ();//default configuration
try {
Httpclient.start ();
HttpGet request = new HttpGet ("http://www.apache.org/");
futureHttpResponse response = Future.get ();//Get Results
System.out.println ("Response:" + response.getstatusline ());
SYSTEM.OUT.PRINTLN ("shutting down");
} finally {
Httpclient.close ();
}
System.out.println ("Done");
}
}
Synchronizer (Synchronizer) is an object that enables threads to wait on another thread, allowing them to collaborate, the most commonly used Synchronizer being countdownlatch and semaphore. Less commonly used are cyclicbarrier and exchanger. The semaphore class is a count semaphore. Conceptually, semaphores maintain a set of licenses. If necessary, block each acquire () before the license is available, and then obtain the license. Each release () adds a license that may release a blocked fetch. However, instead of using the actual license object, Semaphore only counts the number of available licenses and takes action accordingly. Countdownlatch is a synchronous helper class that allows one or more threads to wait until a set of operations that are performed in another thread is completed. Initializes the countdownlatch with the given count. Because the countdown () method is called, the await method is blocked until the current count reaches 0. After that, all the waiting threads are freed, and all subsequent calls to await are returned immediately. This behavior occurs only once-the count cannot be reset. If you need to reset the count, you can use Cyclicbarrier. Inverted-count latches (Countdownlatch) are a one-time barrier. Its unique constructor has a parameter of type int, which is the number of times that the countdown () method must be called on the latch before all wait threads are allowed to process. This is very useful. The following is an example of an asynchronous request for a set of URLs, using the callback pretext to complete a separate operation.
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;
/**
* This example demonstrates a fully asynchronous execution of multiple HTTP
* Exchanges where the result of an individual operation is reported using a
* Callback interface.
*/
public class Asyncclienthttpexchangefuturecallback {
public static void Main (final string[] args) throws Exception {
Requestconfig requestconfig = Requestconfig.custom ()
. SetSocketTimeout (Setconnecttimeout). build ();
Closeablehttpasyncclient httpclient = Httpasyncclients.custom ()
. Setdefaultrequestconfig (Requestconfig). build ();
try {
Httpclient.start ();
Final httpget[] requests = new httpget[] {
New HttpGet ("http://www.apache.org/"),
New HttpGet ("https://www.verisign.com/"),
New HttpGet ("http://www.google.com/"),
New HttpGet ("http://www.baidu.com/")};
Final Countdownlatch latch = new Countdownlatch (requests.length);
For (final HttpGet request:requests) {
Httpclient.execute (Request, new futurecallbackCall Countdown () regardless of completion or failure
@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");
}
}
Reference Document: Http://hc.apache.org/httpcomponents-asyncclient-dev/examples.html
Java uses httpasyncclient for asynchronous HTTP requests