REST timeouts

In this example, we will see how to use the timeouts on the JAX-RS asynchronous methods:

@GET
@Path("/withTimeout")
public void asyncGetWithTimeout(@Suspended final AsyncResponse asyncResponse) {
asyncResponse.setTimeoutHandler(new TimeoutHandler() {
@Override
public void handleTimeout(AsyncResponse asyncResponse) {
asyncResponse.resume(status(SERVICE_UNAVAILABLE).entity("Operation time out.").build());
}
});
asyncResponse.setTimeout(1, SECONDS);
new Thread(new Runnable() {
@Override
public void run() {
String result = ...
asyncResponse.resume(result);
}
}).start();
}

Timeouts are not defined by default on the suspended resource instance; so, we risk endless expectations in some cases. We can use the setTimeoutHandler method to configure a timeout event handler and the setTimeout(Long, TimeUnit) method directly to the resource. The setTimeoutHandler() method represents a handler that will be invoked when timeout is reached so that we can add additional operations to unlock the endless call. In this sample, the handler resumes the response by sending a 503 Service Unavailable response code represented by the javax.ws.rs.core.Response.Status.SERVICE_UNAVAILABLE enum.

We can also define a timeout interval without the custom timeout handler, using just the setTimeout method. As defined by the JAX-RS specification, a default handler will be used by the RESTEasy runtime after the expiration, throwing a javax.ws.rs.ServiceUnavailableException mapped by default with the 503, HTTP error response.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.120.133