Decide at run time for synchronization or asynchronous response using Jersey

Is it possible at runtime to decide whether to process a REST request to a resource endpoint synchronously or asynchronously? Take a simple example.

Synchronous version:

@Path("resource")
public class Resource {
    @GET
    @Produces({MediaType.TEXT_PLAIN})
    public Response get() {
        return Response.ok("Hello there!").build();
    }
}

Asynchronous version:

@Path("resource")
public class Resource {
    @GET
    @Produces({MediaType.TEXT_PLAIN})
    public void get(@Suspended final AsyncResponse r) {
        r.resume(Response.ok("Hello there!").build()); // usually called somewhere from another thread
    }
}

Depending on certain parameters, at runtime I would like to decide whether to process the GET request synchronously or asynchronously. The resource endpoint URL ( http://server/resource) must be the same in both cases. Is it possible?

Of course, as you can see in the above example, the synchronous version can be faked asynchronously, just by calling AsyncResponse.resume(...). However, I would like to avoid the overhead of creating an asynchronous response.

+4
2

API JAX-RS , . , .

API :

, , . , -, - . - .

, , .

URL- , pre-matching filter, ,

, ContainerRequestFilter, @PreMatching , (, ..), URI:

@Provider
@PreMatching
public class PreMatchingFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        if (requestContext.getHeaders().get("X-Use-Async") != null) {
            requestContext.setRequestUri(yourNewURI);
        }
    }
}

ContainerRequestContext API.

, . URL , , .

:

  • : @Consumes("application/vnd.example.sync+text")
  • : @Consumes("application/vnd.example.async+text")

PreMatchingFilter Content-Type , :

if (useSync) {
    requestContext.getHeaders().putSingle(
        HttpHeaders.CONTENT_TYPE, "application/vnd.example.sync+text");
} else {
    requestContext.getHeaders().putSingle(
        HttpHeaders.CONTENT_TYPE, "application/vnd.example.async+text");
}

, ContainerRequestContext#getHeaders() .

+3

MediaType... , , @Produces ( "" ) get @Produces ( "asynch" ) get. Accept Header "" "" , .

0

Source: https://habr.com/ru/post/1615414/


All Articles