Chapter 13. Asynchronous JAX-RS
Another interesting new feature introduced in JAX-RS 2.0 is asynchronous request and response processing both on the client and server side. If you are mashing together a lot of data from different websites or you have something like a stock quote application that needs to push events to hundreds or thousands of idle blocking clients, then the JAX-RS 2.0 asynchronous APIs are worth looking into.
AsyncInvoker Client API
The client asynchronous API allows you to spin off a bunch of HTTP requests in the background and then either poll for a response, or register a callback that is invoked when the HTTP response is available. To invoke an HTTP request asynchronously on the client, you interact with the javax.ws.rs.client.AsyncInvoker
interface or the submit()
methods on javax.ws.rs.client.Invocation
. First, let’s take a look at polling HTTP requests that are run in the background.
Using Futures
The AsyncInvoker
interface has a bunch of methods that invoke HTTP requests asynchronously and that return a java.util.concurrent.Future
instance. You can use the AsyncInvoker
methods by invoking the async()
method on the Invocation.Builder
interface.
package
javax
.
ws
.
rs
.
client
;
public
interface
AsyncInvoker
{
Future
<
Response
>
get
();
<
T
>
Future
<
T
>
get
(
Class
<
T
>
responseType
);
Future
<
Response
>
put
(
Entity
<?>
entity
);
<
T
>
Future
<
T
>
put
(
Entity
<?>
entity
,
Class
<
T
>
responseType
);
Future
<
Response
>
post
(
Entity
<?>
entity
);
<
T
>
Future
<
T
>
post
(
Entity
<?>
entity
,
Class
<
T
>
responseType ...
Get RESTful Java with JAX-RS 2.0, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.