简体   繁体   中英

How to continue request processing after sending response from filter in Jersey?

I have a situation where I need to return an "accepted" response for every request received and publish the actual response later to a separate endpoint outside the service.

To implement the 'accepted' Response I implemented a filter.

public class AcknowledgementFilter implements ContainerRequestFilter{

@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
    containerRequestContext.abortWith(Response.accepted().build());
    // call Resource method in new Thread() . <------ ?
}

}

Implementation of service endpoints:

@Path("/vendor")
public class VendorHandler {

@POST
public void addVendor(VendorRequest addVendorRequest)){
    vendor  = new Vendor();
    Client.publish(vendor);  // publish request to an endpoint
    return null;
}

How do I call the addVendor of VendorHandler(or any method depends on request) from the acknowledgement filter?

Is there any other way to implement an accepted response for every request then process the request separately?

You can use AsyncResponse,

@GET
@ManagedAsync
@Produces(MediaType.APPLICATION_JSON)
public void getLives(@Suspended final AsyncResponse asyncResponse,
                     @DefaultValue("0") @QueryParam("newestid") final int newestId,
                     @QueryParam("oldestid") final Integer oldestId) {

    asyncResponse.setTimeoutHandler(asyncResponse1 -> {
        logger.info("reached timeout");
        asyncResponse1.resume(Response.ok().build());
    });

    asyncResponse.setTimeout(5, TimeUnit.MINUTES);

    try {
        List<Life> lives = oldestId == null ?
                Lifes.getLastLives(newestId) : Lifes.getOlderLives(oldestId);

        if (lives.size() > 0) {
            final GenericEntity<List<Life>> entity = new GenericEntity<List<Life>>(lives) {
            };
            asyncResponse.resume(entity);
        } else LifeProvider.suspend(asyncResponse);

    } catch (SQLException e) {
        logger.error(e, e);
        asyncResponse.resume(new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR));
    }

}

Check this Link for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM