Download Jersey 2.1 User Guide

Transcript
Asynchronous Services and Clients
10.2. Client API
The client API supports asynchronous processing too. Simple usage of asynchronous client API is shown
in the following example:
Example 10.5. Simple client async invocation
1
2
3
4
5
6
7
final AsyncInvoker asyncInvoker = target().path("http://example.com/resource/")
.request().async();
final Future<Response> responseFuture = asyncInvoker.get();
System.out.println("Request is being processed asynchronously.");
final Response response = responseFuture.get();
// get() waits for the response to be ready
System.out.println("Response received.");
The difference against synchronous invocation is that the http method call get() is not called on
SyncInvoker [http://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/client/SyncInvoker.html] but on
AsyncInvoker [http://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/client/AsyncInvoker.html]. The
AsyncInvoker is returned from the call of method Invocation.Builder.async() as shown
above. AsyncInvoker offers methods similar to SyncInvoker only these methods do not return a
response synchronously. Instead a Future<...> representing response data is returned. These method
calls also return immediately without waiting for the actual request to complete. In order to get the response
of the invoked get() method, the responseFuture.get() is invoked which waits for the response
to be finished (this call is blocking as defined by the Java SE Future contract).
Asynchronous Client API in JAX-RS is fully integrated in the fluent JAX-RS Client API flow, so that the
async client-side invocations can be written fluently just like in the following example:
Example 10.6. Simple client fluent async invocation
1 final Future<Response> responseFuture = target().path("http://example.com/resou
2
.request().async().get();
To work with asynchronous results on the client-side, all standard Future API facilities can be used. For
example, you can use the isDone() method to determine whether a response has finished to avoid the
use of a blocking call to Future.get().
10.2.1. Asynchronous Client Callbacks
Similarly to the server side, in the client API you can register asynchronous callbacks too. You can use these
callbacks to be notified when a response arrives instead of waiting for the response on Future.get()
or checking the status by Future.isDone() in a loop. A client-side asynchronous invocation callback
can be registered as shown in the following example:
120